First page Back Continue Last page Overview Graphics

List-Comprehension II

More complicated terms can be calculated within list comprehension as well:

>>> x = [2, 4, 6, 8]

>>> y = [3, 0, -5, 1]

>>> [x[i] + y[i] for i in range(4)]

[5, 4, 1, 9]

A list comprehension can consist of an arbitrary number of for/in's. These can be viewed as nested for loops:

>>> first = ["lust", "merci", "fanci", "art", "power", "voice"]

>>> last = ["less", "ful"]

>>> [ f + l for f in first for l in last ]

['lustless', 'lustful', 'merciless', 'merciful', 'fanciless', 'fanciful', 'artless', 'artful', 'powerless', 'powerful', 'voiceless', 'voiceful']