The best way to concatenate lists in Python is Using the + operator, this is easily added the whole of one list behind the other list. Here are the 6 ways to concatenate lists in Python.
Use the +
operator to combine the lists:
- concatenation (+) operator
- Naive Method
- List Comprehension
- extend() method
- ‘*’ operator
- itertools.chain() method
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
Python concatenate lists
Simple example code joining the elements of a particular data structure in an end-to-end manner.
Concatenation operator (+)
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
res = list1 + list2
print("Concatenated list:\n" + str(res))
Output:
Using 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.
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]
for x in list2:
list1.append(x)
print(list1)
List Comprehension
The process of generating a list of elements based on an existing list.
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]
res = [j for i in [list1, list2] for j in i]
print(res)
Python extend() method
This function performs the in-place extension of the first list.
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]
print(list1)
list1.extend(list2)
print(list1)
Python ‘*’ operator
This method is a new addition to list concatenation and works only in Python 3.6+.
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]
res = [*list1, *list2]
print(res)
itertools.chain() method
This method returns the iterable after chaining its arguments in one and hence does not require storing the concatenated list if only its initial iteration is required.
import itertools
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 42]
res = list(itertools.chain(list1, list2))
print(res)
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.