How to Add Two Lists in Python
To add two lists in Python, you can use the + operator, the extend() function, or the itertools.chain() function.
The following examples show how to add two lists in Python using different methods.
Using + Operator
We can use the + operator to add two lists in Python.
Suppose we have the following lists:
# Declare lists
List1 = ['A-12', 'B-45', 'C-78', 'D-102', 'E-96', 'F-53']
List2 = [2, 5, 10, 7, 1, 8]
# Add lists
Result = List1 + List2
# Show list
print("Updated list:", Result)
Output: 👇️
Updated list: ['A-12', 'B-45', 'C-78', 'D-102', 'E-96', 'F-53', 2, 5, 10, 7, 1, 8]
In this example, we use the + operator to concatenate List1 and List2 into a new list Result.
Using extend() Function
We can use the extend() function to add two lists in Python.
Suppose we have the same lists as above.
We can use the following code to add List2 to List1:
# Add lists
List1.extend(List2)
# Show list
print("Updated list:", List1)
Output: 👇️
Updated list: ['A-12', 'B-45', 'C-78', 'D-102', 'E-96', 'F-53', 2, 5, 10, 7, 1, 8]
In this example, we use the extend() function to add the elements of List2 to List1.
Using itertools.chain() Function
We can use the itertools.chain() function to add two lists in Python.
Suppose we have the same lists as above.
We can use the following code to add List1 and List2:
import itertools
# Add lists
result = list(itertools.chain(List1, List2))
# Show list
print("Updated list:", result)
Output: 👇️
Updated list: ['A-12', 'B-45', 'C-78', 'D-102', 'E-96', 'F-53', 2, 5, 10, 7, 1, 8]
In this example, we use the itertools.chain() function to concatenate List1 and List2 into a new list result.