Skip to content
Advertisement

Make a list from multiple list

I have three lists:

list_01 = ['DOG','CAT','BEAR']
list_02 = ['V','W','X','Y','Z']
list_03 = ['A','B','C','D','E','F','G','H']

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

list_04 = ['DOG','V','A','CAT','W','B','BEAR','X','C','Y','D','Z','E','F','G','H']

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:

from itertools import zip_longest

list_01 = ['DOG','CAT','BEAR']
list_02 = ['V','W','X','Y','Z']
list_03 = ['A','B','C','D','E','F','G','H']


list_04 = [n for group in zip_longest(list_01, list_02, list_03) 
           for n in group if n is not None]

# ['DOG', 'V', 'A', 'CAT', 'W', 'B', 'BEAR', 'X', 'C', 'Y', 'D', 'Z', 'E', 'F', 'G', 'H']

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