1

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.

Hamall
  • 283
  • 3
  • 13
  • 1
    Already asked at https://stackoverflow.com/q/9542738/16004728 –  Jan 26 '22 at 08:46
  • 1
    This may be more suitable for [code review](https://codereview.stackexchange.com/). One thing that should be mentioned - the list comprehension will iterate over the whole list, even if you know there is only one element that satisfy the condition, i.e. no short-circuit or lazy evaluation. @enke answer is better in that respect – buran Jan 26 '22 at 08:49

2 Answers2

3

You can use next:

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

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__()
Delta
  • 362
  • 1
  • 8