Skip to content Skip to sidebar Skip to footer

Nested List Comprehension / Merging Nested Lists

I have a problem understanding a nested list comprehension structure. I have a list >>> test [[1, 2, 3], [4, 5], [6, 7, 8]] If I do t2=[] for x in test: for y in x:

Solution 1:

In your code, before starting, x = [6, 7, 8] from your previous loop (as pointed out by jonsharpe).

Therefore, it unfolds as such:

foryin x:
    forxin test:
        t3.append(y)

x in the first loop point to [6, 7, 8], and is later reassigned, but that does not change the reference that is used in the first loop. The result would be the same if the second x had a distinct name.

Solution 2:

You need to reverse the for loops:

t3 = [y for x in test for y in x]

otherwise (if you don't run the multi-line version beforehand!) x is undefined. Your code only ran on a fluke - x was still what it was at the end of the previous for loop, hence your results.

Solution 3:

Just making sure you know about itertools chain:

>>>test=[[1, 2, 3], [4, 5], [6, 7, 8]]>>>from itertools import chain>>>list(chain(*test))
[1, 2, 3, 4, 5, 6, 7, 8]

Post a Comment for "Nested List Comprehension / Merging Nested Lists"