How to Merge Concatenate or Append Two Lists in Python
Lists are the most flexible data structure in python. They have many uses from managing files and folders to processing data analysis. In this article, we will discuss how to combine …
Lists are the most flexible data structure in python. They have many uses from managing files and folders to processing data analysis. In this article, we will discuss how to combine (merge, concatenate), append, extend lists in python.
# Merging or Concatenating Two Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]
Python lists can be added together with the ‘+’ operator. The order of elements in the resulting list is the order they appear in the operand lists. Here we have two lists list1
and list2
. We then use the ‘+’ operator to combine these two lists into a new list named merged_list
. Finally, we print out the contents of merged_list
.
# Appending Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.append(list2)
print(list1) # Output: [1, 2, 3, [4, 5, 6]]
In Python, lists can be appended to each other using the append() method of a list. Here we have list1
and list2
. We append list2
to list1
, then print out the contents of list1
.
# Extending Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
In Python, the extend() method can also be used to add items from one list into another list. Here we have list1
and list2
. We extend list1
with list2
, then print out the contents of list1
. The extend() method does not return a value, instead it adds the values of the second list to the first.
# Merging Lists Using '+=' Operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 += list2
print(list1) # Output: [1, 2, 3, 4, 5, 6]
The ‘+=’ operator can be used to add two lists together. Here we have list1
and list2
. We then add them together with the ‘+=’ operator, and print out the contents of list1
.