Skip to content
Advertisement

Make a list from multiple list

I have three lists:

JavaScript

What I hope to get is a list like the following:

JavaScript

This list is supposed to contain one item from list 1, then one from list 2, and one from list 3. This then continues until list 1 is exhausted; list 1 should then be ignored, and the same process should happen on just lists 2 and 3, continuing until all lists are empty.

Advertisement

Answer

It seems like you want to do this in order, not randomly. If so, you can use zip_longest() from itertools and make a nested list comprehension:

JavaScript

Note: zip_longest will produce None values when one list runs out. That’s why we are filtering for None in the comprehension.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement