Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Ways to concatenate multiple lists in Python

Ways To Concatenate Multiple Lists In Pythn

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.

Techniques to concatenate multiple lists in Python

Either of the following techniques can be used to concatenate two or more lists altogether:

  • By using itertools module
  • By using Python ‘+’ operator
  • By using Python ‘*’ operator

1. Using Python itertools.chain() method

Python 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 ‘*’ operator

Python '*' 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 “+” operator

Python '+' 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]

Conclusion

Thus, in this article, we have unveiled different ways to concatenate multiple lists in Python.


References

Ways to concatenate list in Python

Leave a Reply

Your email address will not be published. Required fields are marked *