Append multiple lists at once in Python

PythonServer Side ProgrammingProgramming

For various data analysis work in python we may be needed to combine many python lists into one list. This will help processing it as a single input list for the other parts of the program that need it. It provides performance gains by reducing number of loops required for processing the data further.

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.

Example

 Live Demo

listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

# Given lists
print("Given list A: " ,listA)
print("Given list B: " ,listB)
print("Given list C: ",listC)

# using + operator
res_list = listA + listB + listC

# printing result
print("Combined list is : ",res_list)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]

With zip

The zip function brings together elements form each of the lists from the same index and then moves on to the next index. This type of appending is useful when you want to preserver the elements form the lists at the same index position together.

Example

 Live Demo

listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

# Given lists
print("Given list A: " ,listA)
print("Given list B: " ,listB)
print("Given list C: ",listC)

# using zip
res_list = list(zip(listA,listB , listC))

# printing result
print("Combined list is : ",res_list)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : [('Mon', '2 pm', 1), ('Tue', '11 am', 3), ('Wed', '1 pm', 6)]

With itertools.chain

The chain function from itertools module can bring the elements of the lists together preserving the sequence in which they are present.

Example

 Live Demo

from itertools import chain

listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

# Given lists
print("Given list A: " ,listA)
print("Given list B: " ,listB)
print("Given list C: ",listC)

# using chain
res_list = list(chain(listA, listB, listC))

# printing result
print("Combined list is : ",res_list)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]
raja
Published on 13-May-2020 17:34:42
Advertisements