'Unpack the list and put as variable

I have source code like this

chain accept the multple number of lists.

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3]

chain(list1,list2,list3)

However I want to treat list1 list2 list3 as one list and put this in chain

total = [list1,list2,list2] 

chain(total) # it doesn't work , ochain doesn't accept the list.

Is there any good way to do this?



Solution 1:[1]

Use itertools.chain.from_iterable

from itertools import chain

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [1, 2, 3]

total = [list1, list2, list3] 
result = chain.from_iterable(total)
>>> list(result)
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Solution 2:[2]

This is working.


from itertools import chain

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3]

print(list(chain(list1,list2,list3))) # you need to convert chain object to list.

There is a simple way using pure python.

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3]

output_list = list1+list2+list3
print(output_list)

Solution 3:[3]

Another easy way to do this (without extra lib):

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3]

result = [*list1,*list2,*list3]

print(result)
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 annonymous
Solution 2 Sharim Iqbal
Solution 3 Rabinzel