3

I have a sample list of lists like:

lol = [[1,2,3,4],[5,6],[7,8,9,0,11],[21]]

the expected combined list is:

cl = [1,5,7,21,2,6,8,3,9,4,0,11]

Is there an elegant way of doing this preferably without nested for loops?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Sharath
  • 73
  • 3

3 Answers3

5

You can use itertools.zip_longest:

from itertools import zip_longest

lol = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 0, 11], [21]]

out = [i for v in zip_longest(*lol) for i in v if not i is None]
print(out)

Prints:

[1, 5, 7, 21, 2, 6, 8, 3, 9, 4, 0, 11]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

itertools is your friend. Use zip_longest to zip ignoring the differing lengths, chain it to flatten the zipped lists, and then just filter the Nones.

lol = [[1,2,3,4],[5,6],[7,8,9,0,11],[21]]
print([x for x in itertools.chain.from_iterable(itertools.zip_longest(*lol)) if x is not None])
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
1

In case it helps, a generator version of zip_longest is available as more_itertools.interleave_longest.

from more_itertools import interleave_longest, take

lol = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 0, 11], [21]]
gen_from_lol = interleave_longest(*lol)

print(next(gen_from_lol), next(gen_from_lol))
print(take(6, gen_from_lol))
print(next(gen_from_lol))
print(next(gen_from_lol), next(gen_from_lol))

Output

1 5
[7, 21, 2, 6, 8, 3]
9
4 0

Note that interleave_longest(*iterables) is the basically the same as chain.from_iterable(zip_longest(*iterables))

Jamie Deith
  • 706
  • 2
  • 4