Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Merge Two Lists into One

Python Merge Two Lists into One

Document Object Reference Manual Python3 Examples

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

print

(

"Merged list:"

,

merged_list

)

Code analysis:

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

)

print

(

"Merged list:"

,

list1

)

Code analysis:

Output result:

合并后的列表: [1, 2, 3, 4, 5, 6]

Both methods can effectively merge two lists; which one to choose depends on your specific needs.

Document Object Reference Manual Python3 Examples