Skip to content

Instantly share code, notes, and snippets.

@LuRsT
Last active March 17, 2017 10:52
Show Gist options
  • Select an option

  • Save LuRsT/a52c134b70148216d97bea16d6b42242 to your computer and use it in GitHub Desktop.

Select an option

Save LuRsT/a52c134b70148216d97bea16d6b42242 to your computer and use it in GitHub Desktop.
List Comprehensions in Python
# Why list comprehensions?
fruits = ['orange', 'apple', 'pineapple']
things = ['potato', 'orange', 'car', 'apple']
# This will filter things and will create a new list with only fruits from
# things
new_list_of_things = []
for thing in things:
if thing in fruits:
new_list_of_things.append(thing)
# >>> print (new_list_of_things)
# >>> ['orange', 'apple']
# We can re-do that in a more clear way in list comprehensions
# This will just give us a copy of the original list
new_list_of_things = [thing for thing in things]
# >>> print (new_list_of_things)
# >>> ['potato', 'orange', 'car', 'apple']
# ...but we can also do conditions inside the list comprehension:
new_list_of_things = [thing for thing in things if thing in fruits]
# >>> print (new_list_of_things)
# >>> ['orange', 'apple']
# This is exactly what we did above, in just one line and without creating an
# empty list beforehand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment