+ 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)
4 Respuestas
+ 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
+ 3
Thanks! I love the idea of transforming list comprehension to regular for cycles for clarification. Also congratulations for the Comprehensions Tutorial :)
+ 2
HonFu it should be
b.append(x)
instead of
a. append(x)
😉
+ 2
Thomas, absolutely right - corrected. :)