4

I'm trying to understand what does the following python code do

plain_list = [ j for i in arguments for j in i ]

I've never seen such a syntax, can someone help me out?

Bach
  • 6,145
  • 7
  • 36
  • 61
paulAl
  • 949
  • 2
  • 10
  • 17
  • 5
    It's called a list comprehension. Knowing that, you should be able to look it up. – BrenBarn Mar 04 '14 at 19:26
  • Relevant reading: [Advanced list comprehension syntax](http://stackoverflow.com/q/3766711/198633) – inspectorG4dget Mar 04 '14 at 19:29
  • Note that this is a relatively common idiom for flattening a list of lists (iterable of iterables), often used by people who tend not to import `itertools` for everything (`itertools.chain` can be used to the same end.) – DSM Mar 04 '14 at 19:31
  • 1
    OP: welcome to Python, where the first step for doing anything is "How can I reduce that to a list comprehension?" Then the second step is "Oh that's ridiculous, I should just use `itertools` instead." – Adam Smith Mar 04 '14 at 19:33

1 Answers1

13

It is called a list comprehension.

Using normal for-loops, its equivalent code would be:

plain_list = []               # Make a list plain_list
for i in arguments:           # For each i in arguments (which is an iterable)
    for j in i:               # For each j in i (which is also an iterable)
        plain_list.append(j)  # Add j to the end of plain_list

Below is a demonstration of it being used to flatten a list of lists:

>>> arguments = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
>>> plain_list = [ j for i in arguments for j in i ]
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> plain_list = []
>>> for i in arguments:
...     for j in i:
...         plain_list.append(j)
...
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>