Skip to content

Python merge two lists in order

  • by

Use + operator to merge two lists in order in Python. This is the easiest and most recommended way.

list1 + list2

Using list concatenation with the + operator is a straightforward way to merge lists. Alternatively, you can use the extend() method to add elements of one list to another list in place.

Python merges two lists in order

Simple example code.

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)

Output:

Python merge two lists in order

Another way to join two lists is by appending all the items from list2 into a list1, one by one:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

for x in list2:
    list1.append(x)

print(list1)

Or you can use the extend() method, whose purpose is to add elements from one list to another list:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Sorted lists are the ones that are arranged either in ascending or descending order, and merging these sorted lists refers to combining both the two lists in such a way that they remain sorted.

Combining two sorted lists in Python

just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..or shorter (and without modifying):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading