How to Append one List to Another List in Python
In this tutorial, we will learn how to combine Python lists in various ways.
Append List to Another List
To append one list to another list in Python use the .extend()
function. Pass the first list before the function and the list to append as the first argument of the function.
list_1 = [1,2,3]
list_2 = [4,5,6]
list_1.extend(list_2)
print(list_1)
[1, 2, 3, 4, 5, 6]
Note - you can only append one list at a time using the .extend()
function.
Combining Many Lists
To combine many lists together in one statement import itertools
, use the chain method and pass a comma-separated list of lists to combine. Store the result in a new variable.
import itertools
list_1 = [1,2,3]
list_2 = [4,5,6]
lists = itertools.chain(list_1, list_2)
for n in lists:
print(n)
1
2
3
4
5
6
Combine a List inside Another List
To add a list inside another list use the .append()
function.
list_1 = [1,2,3]
list_2 = [4,5,6]
list_1.append(list_2)
print(list_1)
[1, 2, 3, [4, 5, 6]]