Python Forum

Full Version: Comprehension Expressions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Migrated from the old forum, originally posted 22 February 2013.]

Comprehensions are syntactic sugar for for loops. Here is code to create a list without a comprehension
squares = []
for x in xrange(10):
    squares.append(x**2)
Three lines for something simple like that? Not in Python! Here's the same thing as a list comprehension

squares = [x**2 for x in xrange(10)]
What about if we want to exclude certain x values?
squares = [x**2 for x in xrange(10) if x % 2 != 0]
Nested values are possible as well, and can be used to make two or more dimensional lists
>>> two_dimensional = [[x for x in xrange(y*3, y*3 + 3)] for y in xrange](3)
>>> for row in two_dimensional:
   print row

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
What if we had the two_dimensional variable and we wanted to flatten it into a one dimensional one with list comprehension?
>>> [element for row in two_dimensional for element in row]

[0, 1, 2, 3, 4, 5, 6, 7, 8]
We typically think of reading comprehensions backwards as compared to loops.

Not only are there list comprehensions, but there are comprehensions for generators, sets and dictionaries as well. Here is the syntax

>>> squares_set = {x**2 for x in xrange(10)}
>>> squares_set
set([0, 1, 4, 81, 64, 9, 16, 49, 25, 36])
>>> 
>>> squares_dict = {x: x**2 for x in xrange(10)}
>>> squares_dict
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> 
>>> squares_generator = (x**2 for x in xrange(10))
>>> squares_generator
<generator object <genexpr> at 0x7f9cfc0485f0>
>>> sum(squares_generator)
285
>>> sum(squares_generator)
0
>>> sum(x for x in xrange(10))
45

Note that the set and dictionary syntax is very similar, and that a generator, once exhausted is empty. If this behavior is puzzling, you should review generators, which are their own topic.

Feedback always appreciated!