0

This answer https://stackoverflow.com/a/7947190/5517459 gives:

>>> l1=[1,2,3]
>>> l2=[10,20,30]
>>> l3=[101,102,103,104]
>>> [y for x in map(None,l1,l2,l3) for y in x if y is not None]
[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]

This snippet does exactly what I want for my project but it doesn't work in python3.

I've worked around the errors using:

func = lambda *x: x
modules = [y for x in map(func,l1,l2,l3) for y in x]

but it now can't handle variable-length lists, now stopping once it exhausts the shortest list.

Goods
  • 225
  • 2
  • 10

2 Answers2

1

Looks like you need itertools.zip_longest

from itertools import zip_longest
l1=[1,2,3]
l2=[10,20,30]
l3=[101,102,103,104]

print([y for x in zip_longest(l1,l2,l3, fillvalue=None) for y in x if y is not None])

Output:

[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

If they are lists you can also pad all lists with None:

longest_len = max(len(l1), len(l2), len(l3))
zipped_lists = zip(
    l1+[None]*(longest_len-len(l1)),
    l2+[None]*(longest_len-len(l2)),
    l3+[None]*(longest_len-len(l3)))
modules = [y for x in zipped_lists for y in x if y is not None]
Mehdi
  • 4,202
  • 5
  • 20
  • 36