Enumerate an iteration using "i for j in", which I have never seen

I am trying to understand what the following python code does

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

I have never seen such a syntax, can anyone help me?

+4
source share
1 answer

It is called a concept.

Using the usual 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

The following is a demonstration that it is 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]
>>>
+12
source

Source: https://habr.com/ru/post/1530085/


All Articles