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 :
for i in range(4):
print(i*2)

0
2
4
6


Using list comprehension for the same effect.

In :
lst = [i*2 for i in range(4)]

In :
lst

Out:
[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 :
lst = [i*2 for i in range(4) if i%2 == 0]

In :
lst

Out:
[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 :
sum(lst)

Out:
4

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

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

Out:
4

### Dictionary Comprehension¶

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

In :
dict((i*2, i*4) for i in range(4) if i%2 == 0)

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

Out:
{0: 0, 4: 8}

### Set Comprehension¶

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

In :
set(i*2 for i in range(4) if i%2 == 0)

Out:
{0, 4}
In :
{i*2 for i in range(4) if i%2 == 0}

Out:
{0, 4}
Tags: