0
Flatten a list using listcomp with two 'for'
# flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] I don't understand the syntax inside the [] of the second code line. Can anyone shed some light? List comprehension is an awesome tool. Thanks in advanced guys.
3 Respuestas
+ 4
@Juan
This is a wonderfull thing in Python.
In most other and all older languages if you wanted to iterate through a list/array you have use the index of the item in the list/array I.e.
for( i= 0;i<len(vec);i ++)
{do something with vec[i]}
in Python
for elem in vec:
do something with elem
Python is dynamically typed. as you type it creates a var called elem which is equal vec[i] in the example above it.
that is the beauty of python
+ 2
It basically the same as a nested for like:
vec = [[1,2,3],[4,5,6],[7,8,9]]
l = []
for elem in vec:
for num in elem:
l.append(num)
print(l)
+ 2
They are just identifiers like a variable. You can name them whatever you wish as long as it follows the same naming rules python uses for its other variables. elem will be the identifier name for each sub list with the list vec. So the first iteration of the outer for loop elem will be the same as saying vec[0] which is [1,2,3] and the next would be vec[1] which is [4,5,6] etc. num will do the same for each sublist. So during the first iteration of the outer loop when elem is [1,2,3], the first iteration of the inner loop num will be the same as elem[0] which is 1 and so on. List comprehension will usually output/return a new list from the operation within it. This is why you end up with a new list made up of the values from within the inner lists of vec.