+

Python | Add multiple lists at the same time

Method # 1: Using the +
Operator This is easy to do with the plus operator, since it adds an item to the end of the list. This logic extends to the case of multiple lists.

# Python3 demo code
# add immediately multiple lists
# using the + operator

 
# initializing lists

test_list1 = [ 1 , 3 , 5 , 5 , 4 ]

test_list2 = [ 4 , 6 , 2 , 8 , 10 ]

test_list3 = [ 7 , 5 , 2 , 9 , 11 ]

  
# printing original lists

print ( "The original list 1 is:" + str (test_list1))

print ( "The original list 2 is:" + str (test_list2))

print ( "The original list 3 is:" + str (test_list3))

 
# using the + operator
# adding multiple lists at once

test_list1 = test_list1 + test_list2 + test_list3

  
# print result

print ( "The extended and modified list is:" +   str (test_list1))

Exit:

The original list 1 is: [1, 3, 5, 5, 4]
The original list 2 is: [4, 6, 2, 8, 10]
The original list 3 is: [7, 5, 2, 9, 11]
The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]

Method # 2: Using itertools.chain()
The chaining function can also be used to accomplish this specific task as it uses an iterator to accomplish this task and therefore offers better performance compared with the above method.

# P ython3 demo code
# adding multiple lists at once
# using itertools.chain ()

from itertools import chain

 
# initializing lists

test_list1 = [ 1 , 3 , 5 , 5 , 4 ]

test_list2 = [ 4 , , 2 , 8 , 10 ]

test_list3 = [ 7 , 5 , 2 , 9 , 11 ]

  
# printing original lists

print ( " The original list 1 is: " + str (test_list1 ))

print ( " The original list 2 is: " + str (test_list2))

print ( "The original list 3 is:" + str (test_list3))

 
# using itertools .chain ()
# adding multiple lists at once

test_list1 = list (chain (test_list1, test_list2, test_list3))

 
# print result

print ( "The extended and modified l ist is: " +   str (test_list1))

Exit:

The original list 1 is: [1, 3, 5, 5, 4]
The original list 2 is: [4, 6, 2, 8, 10]
The original list 3 is: [7, 5, 2 , 9, 11]
The extended and modified list is: [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]

Get Solution for free from DataCamp guru