Learn about generators, list, dictionary and set comprehensions.
Python Comprehensions

List, Dictionary and Set Comprehensions

List Comprehension

Normal for loop that can be later done with list comprehension.

In [2]:
for i in range(4):
    print(i*2)
0
2
4
6

Using list comprehension for the same effect.

In [3]:
lst = [i*2 for i in range(4)]
In [4]:
lst
Out[4]:
[0, 2, 4, 6]

You can make more complicated list comprehensions like multiplying only if it's a multiple of 2. I do all sorts of crazy things with list comprehensions.

In [5]:
lst = [i*2 for i in range(4) if i%2 == 0]
In [6]:
lst
Out[6]:
[0, 4]

Take note that this creates a list in memory where you can manipulate later. But if you do not need a list, you can use a generator expression.

Generator Expression

PEP289 Abstract

The utility of generator expressions is greatly enhanced when combined with reduction functions like sum(), min(), and max(). The heapq module in Python 2.4 includes two new reduction functions: nlargest() and nsmallest(). Both work well with generator expressions and keep no more than n items in memory at one time.

For example, we can sum the list we made above.

In [8]:
sum(lst)
Out[8]:
4

If you do not want it in memory, simply use generator expressions.

In [9]:
sum(i*2 for i in range(4) if i%2 == 0)
Out[9]:
4

Dictionary Comprehension

This is similar to what we've above, where you can use dict() or {}.

In [12]:
dict((i*2, i*4) for i in range(4) if i%2 == 0) 
Out[12]:
{0: 0, 4: 8}
In [17]:
{i*2: i*4 for i in range(4) if i%2 == 0}
Out[17]:
{0: 0, 4: 8}

Set Comprehension

There are two ways to do this: set() or {}

In [18]:
set(i*2 for i in range(4) if i%2 == 0)
Out[18]:
{0, 4}
In [19]:
{i*2 for i in range(4) if i%2 == 0}
Out[19]:
{0, 4}
Tags: python