Python Merge Two Lists into One
In Python, merging two lists into one can be achieved in multiple ways. The most common method is to use the+operator orextend()method. Below is a simple example showing how to merge two lists into one.
Example
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Use the + operator to merge lists
merged_list = list1 + list2
print("Merged list:", merged_list)
list2 = [4, 5, 6]
# Use the + operator to merge lists
merged_list = list1 + list2
print("Merged list:", merged_list)
Code explanation:
list1andlist2are the two lists to be merged.merged_list = list1 + list2Use the+operator tolist1andlist2merge into a new listmerged_list。print("合并后的列表:", merged_list)Print the merged list.
Output result:
合并后的列表: [1, 2, 3, 4, 5, 6]
You can also use theextend()method to merge lists, as shown below:
Code section:
Example
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Use the extend() method to merge lists
list1.extend(list2)
print("Merged list:", list1)
list2 = [4, 5, 6]
# Use the extend() method to merge lists
list1.extend(list2)
print("Merged list:", list1)
Code explanation:
list1.extend(list2)willlist2elements from are added tolist1the end of.print("合并后的列表:", list1)Print the merged list.
Output result:
合并后的列表: [1, 2, 3, 4, 5, 6]
Both methods can effectively merge two lists. Which method you choose depends on your specific needs.
Other Extensions
Python3 Examples