Python join two lists of lists
In this article, we will understand various techniques to concatenate multiple lists in Python. Python lists provide us a way to store data and perform manipulations on it. Show Techniques to concatenate multiple lists in PythonEither of the following techniques can be used to concatenate two or more lists altogether:
1. Using Python itertools.chain() methodPython itertools module provides us with itertools.chain() method to concatenate multiple lists together. The itertools.chain() method accepts data of different iterables such as lists, string, tuples, etc and provides a linear sequence of elements out of them. This function works irrespective of the data type of the input data. Syntax: itertools.chain(list1, list2, ...., listN)
Example: import itertools
x = [10, 30, 50, 70]
y = [12, 16, 17, 18]
z = [52, 43, 65, 98]
opt = list(itertools.chain(x,y,z))
print ("Concatenated list:\n",str(opt))
Output: Concatenated list:
[10, 30, 50, 70, 12, 16, 17, 18, 52, 43, 65, 98]
2. Using Python * operatorPython '*' operator provides a much efficient way to perform manipulation on the input lists and concatenate them together. It represents and unwraps the data elements at their provided index position. Syntax: [*input_list1, *input_list2, ...., *inout_listN]
As mentioned, the *input_list1, *input_list2, etc would contain elements within that list at the given index in the mentioned order. Example: x = [10, 30, 50, 70]
y = [12, 16, 17, 18]
z = [52, 43, 65, 98]
opt = [*x, *y, *z]
print ("Concatenated list:\n",str(opt))
Output: Concatenated list:
[10, 30, 50, 70, 12, 16, 17, 18, 52, 43, 65, 98]
3. Using Python + operatorPython '+' operator can be used to concatenate the lists together. Syntax: list1 + list2 + .... + listN
Example: x = [10, 30, 50, 70]
y = [12, 16, 17, 18]
z = [52, 43, 65, 98]
opt = x+y+z
print ("Concatenated list:\n",str(opt))
Output: Concatenated list:
[10, 30, 50, 70, 12, 16, 17, 18, 52, 43, 65, 98]
ConclusionThus, in this article, we have unveiled different ways to concatenate multiple lists in Python. ReferencesWays to concatenate list in Python |