How does this double loop list creation work?

51 views Asked by At

The top answer to Interleave multiple lists of the same length in Python uses a really confusing syntax to interleave two lists l1 and l2:

l1 = [1,3,5,7]
l2 = [2,4,6,8]
l3 = [val for pair in zip(l1, l2) for val in pair]

and somehow you get l3 = [1,2,3,4,5,6,7,8]

I understand how list comprehension with a single "for z in y" statement works, and I can see that somehow we're looping through the zip, and within that through each tuple. But how does that turn a list of four tuples into an interleaved list of eight? Totally bewildered by this line of code.

1

There are 1 answers

0
TanjiroLL On

zip returns pair of items from the two list as follows:

l_pair = [val for val in zip(l1, l2)]
print(l_pair) # [(1, 2), (3, 4), (5, 6), (7, 8)]

So zip will return a list(it actually returns a generator) of tuples, first item from the first list, and second item from the second list.

So for each pair, we add the first item, then the second item of it.

l = []
for pair in l_pair:
  for elem in pair:
    l.append(elem)
print(l) # [1, 2, 3, 4, 5, 6, 7, 8]