Easy to comprehend list comprehensions

This is the introduction to list comprehensions that I wish I had read when I first encountered them. There are other good introductions to list comprehensions, but I wrote this one based on a very simple concept: Every list comprehension evaluates to the list [1,2,3] This should make it easy to follow the examples as they go from very trivial to more complex.

tl;dr Every example here evaluates to [1,2,3]


In [10]:
#reductio ad absurdum

foo = [x for x in [1,2,3]]

print foo


[1, 2, 3]

In [11]:
# bar is a list which is an iterable object

bar = [1,2,3]

foo = [x for x in bar]

print foo


[1, 2, 3]

In [13]:
# a list comprehension can work with anything thats an iterable object,
# like the range() function

foo = [x for x in range(1,4)]

print foo


[1, 2, 3]

In [18]:
# on the left side of the list comp you can do stuff to the individual elements
# as they come out of the iterator

foo = [x+11 for x in range(-10,-7)]

print foo


[1, 2, 3]

In [19]:
# here bar is a string which is also an iterable object

bar = "123"

foo = [x for x in bar]

print foo


['1', '2', '3']

In [23]:
# side quest: .split() is very useful for getting at things in a string
# that are separated by something

bar = "1$2$3"

foo = [x for x in bar.split('$')]

print foo


['1', '2', '3']

In [26]:
# this is no better than foo =  bar.split(‘$’) except that it allows you to get at each 
# result of .split() That’s useful if you want to do something like force each item 
# to be an integer:

foo = [int(x) for x in bar.split('$')]

print foo


[1, 2, 3]

In [28]:
# If statements can be used on the right side of a list comprehension to filter 
# what is coming out of the iterator 

foo = [x for x in range(1,100) if x <= 3]

print foo


[1, 2, 3]

In [34]:
# here is how to check if the items coming out of the iterator
# are in another list

wat = [1,2,3]

bar = [-1,0,1,2,3]

foo = [x for x in bar if x in wat] # returns the actual values

print foo


[1, 2, 3]

In [41]:
# bool_foo is a list that is the same length as bar, 
# with True or False for each element depending on if it is in the list wat. 
# This is super useful for filtering pandas data frames

bool_foo =  [(x in wat) for x in bar] 

print bar
print bool_foo


[-1, 0, 1, 2, 3]
[False, False, True, True, True]