Skip to content
Advertisement

Best way to get element in list

I’m wondering what is the best way to return specific element in list based on specific condition, we can assume that there is always one and only one element that satisfy that condition.

Example :

period = [p for p in periods if str(p.end) == date][0] 

The previous snip of code works, but i don’t really like access to result with [0] on the final list.

Advertisement

Answer

You can use next:

period = next((p for p in periods if str(p.end) == date), None) 
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement