Last active
August 29, 2015 14:06
-
-
Save jangeador/548d8efb759129f874a4 to your computer and use it in GitHub Desktop.
Find object in list of objects or return None
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
next((x for x in test_list if x.value == value), None) | |
''' | |
This gets the first item from the list that matches the condition, and returns None if no item matches. It's my preferred single-expression form. | |
However, | |
''' | |
for x in test_list: | |
if x.value == value: | |
print "i found it!" | |
break | |
''' | |
The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner: | |
''' | |
for x in test_list: | |
if x.value == value: | |
print "i found it!" | |
break | |
else: | |
x = None | |
''' | |
This will assign None to x if you don't break out of the loop. | |
Source: <http://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condi> | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment