+ 1
Explanation of list comprehensions
Can anyone tell me how this expression works? l = [[1,2],[3,4],[5,6]] print([a for a in l for a in a])
2 Answers
+ 1
List comprehension allow to shorthand iteration on list...
What's confusing in your example, is the identifier 'a' use twice, at differents variables scopes / override each others, but:
print([a for a in l for a in a])
... can be decomposed like that:
for a in l:
for a in a:
print(a)
... also, for more clarity:
for a in l:
for b in a:
print(b)
So you simply iterate on the 2d array, listing each values, and the output is ( each value at a line ):
1 2 3 4 5 6
0
that one just looka confusing.. so here is another one.
my_list = [num for num in range(10)]
print(my_list)
[0,1,2,3,4,5,6,7,8,9]
the first line does the same thing as the following code:
my_list = []
for num in range(10):
my_list.append(num)