Last Updated: February 25, 2016
·
742
· st3fan

Find the first item in a list

How often have you written something like this:

session = None
for s in scan['sessions']:
    if s['id'] == id:
        session = s
        break

Here is a nice one-liner to replace that:

next((s for s in sessions if s['id'] == id), None)

The None is the default value in case nothing was found.

The list comprehension is lazy so as a nice side effect it will only walk/generate the list as far as needed.

1 Response
Add your response

Nice !

over 1 year ago ·