Explanation of list comprehensions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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])

7th Feb 2017, 2:15 PM
Артём Косенко
Артём Косенко - avatar
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
8th Feb 2017, 9:02 AM
visph
visph - avatar
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)
7th Feb 2017, 10:32 PM
Luke Armstrong