In this tutorial, we will unveil different methods to concatenate or combine together multiple lists in Python. Python Lists serve the purpose of storing homogeneous elements and perform manipulations on the same.
In general, Concatenation is the process of joining the elements of a particular data-structure in an end-to-end manner.
The following are the 6 ways to concatenate lists in Python.
The '+' operator
can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.
Example:
Output:
In the Naive method, a for loop is used to traverse the second list. After this, the elements from the second list get appended to the first list. The first list results out to be the concatenation of the first and the second list.
Example:
Output:
Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list.
It uses for loop to process and traverses the list in an element-wise fashion. The below inline for-loop is equivalent to a nested for loop.
Example:
Output:
Python’s extend() method can be used to concatenate two lists in Python. The extend()
function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion.
Syntax:
Example:
All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.
Output:
Python’s '*' operator
can be used to easily concatenate two lists in Python.
The ‘*’ operator in Python basically unpacks the collection of items at the index arguments.
For example: Consider a list my_list = [1, 2, 3, 4].
The statement *my_list would replace the list with its elements at the index positions. Thus, it unpacks the items of the lists.
Example:
In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output.
Output:
Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python.
The itertools.chain()
function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output.
It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method.
For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny
Example:
Output:
Thus, in this article, we have understood and implemented different ways of Concatenating lists in Python.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.