Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a list from multiple list

Tags:

python

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.

like image 496
Mango Tango Avatar asked Sep 03 '21 16:09

Mango Tango


People also ask

How do I put multiple lists into one list?

Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.

How do I make a list of multiple lists in Python?

You can simply use a for loop to create n lists. The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on. Show activity on this post. there is a way to do that if you want to create variables.

How do I merge three lists?

chain() method is passed the arguments of list1, list2 and list3. This method takes multiple arguments and returns a single sequence of items. So, the chain() method concatenates all three lists. The result of the method call is converted into a list using the list() method.

How do I combine multiple Excel lists into one?

On the Data tab, under Tools, click Consolidate. In the Function box, click the function that you want Excel to use to consolidate the data. In each source sheet, select your data, and then click Add. The file path is entered in All references.


Video Answer


2 Answers

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.

like image 121
Mark Avatar answered Sep 22 '22 21:09

Mark


You can use zip_longest and chain from the itertools module:

from itertools import chain, zip_longest
list_04 = [i for i in chain(*zip_longest(list_01, list_02, list_03))
           if i is not None]

output:

['DOG', 'V', 'A', 'CAT', 'W', 'B', 'BEAR', 'X', 'C', 'Y', 'D', 'Z', 'E', 'F', 'G', 'H']
like image 23
mozway Avatar answered Sep 23 '22 21:09

mozway