+ 3

[x for x in a for x in x] Anyone to explain this?

a = [[1,2],[2,3],[3,4]] b = [x for x in a for x in x] print(b) Output: [1, 2, 2, 3, 3, 4] What I understand: b = [x for x in a] output: [[1, 2], [2, 3], [3, 4]] This is clear but what is second half of the list comprehension above? (...for x in x)

31st Dec 2019, 8:12 AM
Prof. Dr. Zoltán Vass
4 odpowiedzi
+ 8
In regular code, the first example would look like this: b = [] for x in a: for x in x: b.append(x) It's the naming that creates the confusion. For the outer loop, the inner list is called x, then for the inner loop, the name is regiven for the actual number. Works, but messy. b = [x for list_ in a for x in list_] https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
31st Dec 2019, 8:26 AM
HonFu
HonFu - avatar
+ 3
Thanks! I love the idea of transforming list comprehension to regular for cycles for clarification. Also congratulations for the Comprehensions Tutorial :)
31st Dec 2019, 8:30 AM
Prof. Dr. Zoltán Vass
+ 2
HonFu it should be b.append(x) instead of a. append(x) 😉
31st Dec 2019, 8:32 AM
Coding Cat
Coding Cat - avatar
+ 2
Thomas, absolutely right - corrected. :)
31st Dec 2019, 8:41 AM
HonFu
HonFu - avatar