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.
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.
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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With