Last modified: Aug 16, 2026

Python Array Merge & Sort Guide

Combining and ordering data is a core skill in Python. This guide focuses on merging and sorting arrays (or lists) efficiently. You will learn multiple methods, from simple to advanced.

We will use Python lists, which function as dynamic arrays. The techniques cover both small scripts and large datasets. Let's start with the basics and build up.

Why Merge and Sort?

Merging combines multiple data sources into one. Sorting arranges that data for easier analysis or searching. Together, they are essential for tasks like report generation or data preprocessing.

Python offers built-in tools that make this fast and readable. You don't need complex algorithms for most cases. The standard library handles the heavy lifting.

Understanding these methods helps you write cleaner code. It also improves performance compared to manual loops. Let's explore the primary techniques.

Merging Arrays with + and extend()

The simplest way to merge two lists is using the + operator. It creates a new list containing elements from both. This is intuitive and easy to read.


# Using the + operator
list_a = [3, 1, 2]
list_b = [6, 5, 4]

merged = list_a + list_b
print(merged)  # Output: [3, 1, 2, 6, 5, 4]

Another common method is extend(). This modifies the original list in place. It is more memory-efficient than + when you don't need the original list anymore.


# Using the extend() method
list_a = [3, 1, 2]
list_b = [6, 5, 4]

list_a.extend(list_b)
print(list_a)  # Output: [3, 1, 2, 6, 5, 4]

Both methods are fast for typical use cases. Choose + for a new list and extend() for in-place updates. For more on array fundamentals, see our Python Array Module vs List guide.

Sorting with sorted() and list.sort()

Python provides two primary sorting methods. The sorted() function returns a new sorted list. The list.sort() method sorts the list in place.


# Using sorted() - returns a new list
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 5, 9]
print(numbers)         # Original is unchanged: [5, 2, 9, 1]

# Using list.sort() - sorts in place
numbers.sort()
print(numbers)         # Output: [1, 2, 5, 9]

Both methods accept a reverse=True parameter for descending order. They also support a key parameter for custom sorting logic. This is powerful for sorting dictionaries or objects.


# Sorting with a key and reverse
words = ["banana", "apple", "cherry"]
words.sort(key=len, reverse=True)
print(words)  # Output: ['banana', 'cherry', 'apple']

Use sorted() when you need the original list intact. Use list.sort() for memory efficiency. For more on iterating through arrays, check our Python Array Iteration Guide.

Merge Then Sort: Simple Approach

The most straightforward strategy is to merge first, then sort. You combine all elements into one list. Then apply a sorting function to the result.


# Merge and then sort
list1 = [3, 1, 4]
list2 = [2, 5, 0]

merged_list = list1 + list2
merged_list.sort()
print(merged_list)  # Output: [0, 1, 2, 3, 4, 5]

This approach is simple and works well for small to medium lists. It is easy to understand and debug. However, it creates an intermediate list before sorting.

For most applications, this is perfectly fine. The performance is O(n log n) for sorting, which is optimal. The merge itself is O(n). This is a clean and readable solution.

Efficient Merging with heapq.merge()

For large sorted lists, heapq.merge() is more efficient. It merges multiple sorted inputs into a single sorted output. It does not load all data into memory at once.


# Using heapq.merge for sorted lists
import heapq

list1 = [1, 3, 5]
list2 = [2, 4, 6]

merged = list(heapq.merge(list1, list2))
print(merged)  # Output: [1, 2, 3, 4, 5, 6]

This function returns an iterator. You can convert it to a list with list(). It requires the input lists to be already sorted. It is perfect for merging large sorted files or streams.

It is memory-efficient because it only keeps one item from each list at a time. This makes it ideal for big data scenarios. For more on memory, see our Python Array Memory Allocation article.

Sorting with Custom Keys

Sometimes you need to sort by a specific attribute. For example, sorting a list of tuples by the second element. The key parameter allows this elegantly.


# Sorting a list of tuples by the second element
data = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
data.sort(key=lambda x: x[1])
print(data)  # Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]

You can also use operator.itemgetter() for better performance. It is faster than a lambda for simple attribute access. This is a common optimization for large lists.


# Using itemgetter for speed
from operator import itemgetter

data = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
data.sort(key=itemgetter(1))
print(data)  # Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]

Custom keys work with both sorted() and list.sort(). This flexibility makes Python sorting very powerful. You can sort by any attribute or function result.

Handling Different Data Types

Python can sort lists containing mixed types, but with limitations. Numbers and strings cannot be compared directly. You must convert them to a common type first.


# Mixed types cause errors
mixed = [1, "two", 3]
# mixed.sort()  # This raises TypeError

# Solution: convert to strings for sorting
mixed_str = [str(item) for item in mixed]
mixed_str.sort()
print(mixed_str)  # Output: ['1', '3', 'two']

For arrays from the array module, all elements are the same type. This avoids such issues. If you are working with typed arrays, remember they are different from lists. Check our Type Casting Guide for more details.

Always ensure your data is compatible before sorting. This prevents unexpected errors. It also makes your code more robust and predictable.

Stability of Sorting

Python's sort is stable. This means equal elements retain their original order. This is crucial when sorting on multiple keys.


# Stability in sorting
records = [("A", 1), ("B", 1), ("C", 2)]
records.sort(key=lambda x: x[1])
print(records)  # Output: [('A', 1), ('B', 1), ('C', 2)]
# 'A' stays before 'B' because they are equal

You can leverage stability to sort by multiple criteria. Sort by the primary key first, then by the secondary key. The second sort preserves the first order for equal elements.


# Multi-key sorting using stability
data = [("Bob", 25), ("Alice", 25), ("Bob", 20)]
data.sort(key=lambda x: x[1])  # Sort by age
data.sort(key=lambda x: x[0])  # Sort by name, stable
print(data)  # Output: [('Alice', 25), ('Bob', 20), ('Bob', 25)]

This technique is elegant and efficient. It avoids complex comparison functions. It is a best practice for multi-level sorting.

Performance Considerations

For large arrays, performance matters. The merge-then-sort approach is O(n log n). Using heapq.merge() on sorted lists is O(n).

If your lists are already sorted, use heapq.merge(). It is significantly faster for large datasets. It also uses less memory.

If your lists are unsorted, you must sort them first. Then merge. Or just merge and sort the result. The latter is simpler but may use more memory.

Always profile your code with real data. Premature optimization is not recommended. Start with the simplest solution and optimize only if needed.

Conclusion

Merging and sorting arrays in Python is straightforward. You can use simple operators and built-in functions. For most tasks, + and sorted() are enough.

For large sorted data, heapq.merge() is your best friend. It is fast and memory-efficient. Custom keys give you full control over sorting logic.

Remember to handle mixed data types carefully. Use stable sorting for multi-key scenarios. Practice these methods to become proficient.

These skills are fundamental for data manipulation. They appear in almost every Python project. Master them to write efficient and readable code.