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.
Written by Stefan Arentz
Related protips
1 Response
Nice !
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Related Tags
#python
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#