Hamall
Hamall

Reputation: 293

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.

Upvotes: 1

Views: 176

Answers (2)

Delta
Delta

Reputation: 370

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__()

Upvotes: 1

user7864386
user7864386

Reputation:

You can use next:

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

Upvotes: 3

Related Questions