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?
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?
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]
>>>