List Comprehensions in Python
Archive - Originally posted on "The Horse's Mouth" - 2008-11-06 06:21:08 - Graham EllisHow do you perform an operation on every member of a list, producing a new list? A List Comprehension in Python is a structure in which a for loop is written within a list's square brackets. Its purpose is to allow the programmer to write short code that's used to transform each element of a source list, generating a new list without the need to append new items one by one to that new list. Here are some examples:
squares = [x*x for x in range(10)]
print squares
# result - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
and
breakfast = ["Orange Juice", "Cereal", "Actimel"]
size2 = [len(x) for x in breakfast]
print size2
# result - [12, 6, 7]
One of the more conventional alternatives to a list comprehension is a map function call (but that's more limited). Here is that example we have just see re-coded in the form of a map for comparison:
size1 = map(len,breakfast)
print size1
# result - [12, 6, 7]
But here are some examples that wouldn't be so easy with a map - if (for example) you wanted to run a method on each object in a list, rather than a function on each member:
shout = [x.upper() for x in breakfast]
print shout
# result - ['ORANGE JUICE', 'CEREAL', 'ACTIMEL']
And here's another feature - you can add an if clause onto a list comprehension which allows you to select (filter out) certain records if you wish:
shout = [x.upper() for x in breakfast if x != "Cereal"]
print shout
# result - ['ORANGE JUICE', 'ACTIMEL']
Full source code of this example - here