Tag Archives: losers

Python List Comprehension for Dummies

So I code a lot. I code in Python a lot. You might say I love Python. I might say you’re right.

One of the most powerful things about Python is its ability to iterate over ANYTHING as if it were a list. Lists, tuples, dictionaries, and even strings can all be iterated quickly and elegantly. Python also introduces a concept known as list comprehension which allows you to do rather complex filtering of list contents within a single statement.

To illustrate how awesome and powerful list comprehension is, let’s start with a basic example that is NOT using it:

>>> mylist = [1,2,3,4,5]
>>> for item in mylist:
...     if item % 2 == 0: print item, 'is an even number.'
...
2 is an even number.
4 is an even number.
So, let’s assume that we want to identify all even numbers inside of mylist, and put them into a new list called evens the old-fashoned way:
>>> mylist = [1,2,3,4,5]
>>> evens = []
>>> for item in mylist:
...     if item % 2 == 0: evens.append(item)
...
>>> evens
[2, 4]
Why the old-fashioned way sucks First things first, the empty list called evens had to be declared ahead of time. This is because when we looped thru the list called mylist using the for statement, when the if test is performed on each item we have to reference evens by name to append() the even numbers to it.

Why list comprehension rocks With list comprehension, the logic that isolates the even numbers and the declaration of the list that will capture this output are compressed into a single statement:

>>> mylist = [1,2,3,4,5]
>>> evens = [i for i in mylist if i % 2 == 0 ]
>>> evens
[2, 4]
The logic is encapsulated in [square brackets] indicating that the output will be a list. The list comprehension itself is the logic between the brackets that determines what will be in the list that it spits out.

So list comprehensions at their most basic level allow for compression of code and streamlining of logical statements. Advanced usage of list comprehension can get pretty silly, but then so can nested loop statements.  It supports nesting as many statements as you can throw at it so longs as they are syntactically correct.

If you find yourself coding shit like this:

>>> losers = ['Joe','Jim','Jon','Jen']
>>> for u in losers:
...     if u.startswith('J'):
...             if u.endswith('n'):
...                     if u != 'Jon':
...                             print u
...
Jen
Then maybe list comprehension is for you:
>>> [u for u in losers if u.startswith('J') and u.endswith('n') and u != 'Jon']
['Jen']
No offense to anyone named Joe, Jim, or Jon.