Last active
April 19, 2016 04:09
-
-
Save juzten/38fdcf354d1ecd000b8d to your computer and use it in GitHub Desktop.
For loop that handles if a list could be None instead of having items in a list.
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
# For loop that handles if an item is None instead of having | |
# items in a list. | |
# this is a sqlalchemy query, it will either return a list of people with | |
# the first_name of 'Justin' or if there is no person with that first name | |
# it will return None. This is just an example of when a variable might be | |
# a list with list items or None. | |
# people = Person.query.filter_by(first_name='Justin'.all() | |
# I'm specifically setting people to None here because I'm not calling the sqlalchemy query above. | |
# If people was a list that contained items, the print statements in the for loop would be called. | |
# Since people is set to None, nothing will be printed because empty list in the 'or []' section | |
# is what is evaluated. | |
people = None | |
for person in people or []: | |
print(person.first_name) | |
print(person.last_name) | |
# unlrelated comprehension equiv but same concept | |
result = [do_something(item) for item in a_list() or []] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment