Python Merge Two Lists into One
In Python, merging two lists into one can be done in several ways. The most common method is to use the + operator or the extend() method. Below is a simple example showing how to merge two lists into one.
Example
list1
=
[
1
,
2
,
3
]
list2
=
[
4
,
5
,
6
]
Merge lists using the + operator
merged_list
=
list1 + list2
(
"Merged list:"
,
merged_list
)
Code analysis:
list1andlist2are the two lists to be merged.merged_list = list1 + list2Use+operator mergeslist1andlist2into a new listmerged_list。print("合并后的列表:", merged_list)Output the merged list.
Output result:
合并后的列表: [1, 2, 3, 4, 5, 6]
You can also use the extend() method to merge lists, as shown below:
The code:
Example
list1
=
[
1
,
2
,
3
]
list2
=
[
4
,
5
,
6
]
Merge lists using the extend() method
list1.
extend
(
list2
)
(
"Merged list:"
,
list1
)
Code analysis:
list1.extend(list2)data to the child component vialist2add the elements oflist1end of theprint("合并后的列表:", list1)Output the merged list.
Output result:
合并后的列表: [1, 2, 3, 4, 5, 6]
Both methods can effectively merge two lists; which one to choose depends on your specific needs.
Python3 Examples