0

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
    If you understand `pair in zip(l1, l2)`, then just read around that, e.g. take each item from every tuple, in order. – OneCricketeer Apr 15 '23 at 02:36
  • Also, "top answer" depends on your sorting settings. I do not see this solution at the top, but I see others like using `itertools.chain` - https://stackoverflow.com/a/40954220/2308683 – OneCricketeer Apr 15 '23 at 02:40
  • The `for val in pair` part is just flattening out the tuples that `zip()` gives you. – Peter DeGlopper Apr 15 '23 at 02:44

1 Answers1

4

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]
TanjiroLL
  • 1,354
  • 1
  • 5
  • 5