How to Add Lists Together in Python
To add lists together in Python, you can use the + operator and the extend() function.
The following examples show how to add lists together in Python.
Using + Operator
We can use the + operator to add lists together.
Suppose we have the following lists:
# Declare lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Add lists
new_list = list1 + list2
# Show new list
print("New list:", new_list)
Output: 👇️
New list: [1, 2, 3, 4, 5, 6]
In this example, we use the + operator to concatenate list1 and list2 into a new list new_list.
Using extend() Function
We can use the extend() function to add lists together.
Suppose we have the same lists as above.
We can use the following code to add list2 to list1:
# Add list
list1.extend(list2)
# Show new list
print("New list:", list1)
Output: 👇️
New list: [1, 2, 3, 4, 5, 6]
In this example, we use the extend() function to add the elements of list2 to list1.