Home > other >  Best way to get element in list
Best way to get element in list

Time:01-27

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.

CodePudding user response:

You can use next:

period = next((p for p in periods if str(p.end) == date), None) 

CodePudding user response:

better style I know:

check = None # check(p) -> bool

for p in periods:
    if check(p):
        elem = p
        break
else: # may check don't return True
    elem = None

better for 1 line I know:

elem = (p for p in periods if check(p)).__next__()
  •  Tags:  
  • Related