Generator expressions

A genexp is a convenient way to make a generator.

In [1]:
larkin_poems = ['church going', 'the whitsun weddings', 'an arundel tomb', 'aubade']
title = (poem.title() for poem in larkin_poems)
print(next(title))
print(next(title))
print(next(title))
Church Going
The Whitsun Weddings
An Arundel Tomb

Build sets and dicts without building intermediate lists.

In [2]:
a = set(char for char in 'Loveliest of trees, the cherry now')
b = dict((x, x**2) for x in range(9))

Sometimes avoiding the intermediate lists can save significant amounts of memory (relative to listcomps).

In [11]:
sum_listcomp = sum([x*x for x in range(10000000)])
sum_genexp = sum(x*x for x in range(10000000))