This is a list comprehension.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
The basic structure you'll see often is [EXP for VAR in LIST]
which iterates LIST
, and for each element in the list, EXP
is evaluated with VAR
set to the respective list element.
Let's start with a list x
that contains the integers 0 to 9:
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can use a list comprehension in a similar manner to map()
to alter each element:
>>> [i * 2 for i in x]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
You can use it to filter out elements:
>>> [i for i in x if i % 2 == 0]
[0, 2, 4, 6, 8]
You can do both at the same time:
>>> [i * 2 for i in x if i % 2 == 0]
[0, 4, 8, 12, 16]
You don't even have to reference the iteration variable:
>>> ["foo" for i in x if i % 2 == 0]
['foo', 'foo', 'foo', 'foo', 'foo']
The second example in your question is an example of how to project a list for each element; in this particular case, the outer list being traversed contains iterables. This expression maps the inner iterables to lists. This can be used to map nested lists.