Home > Backend Development > Python Tutorial > How to Efficiently Merge Pre-Sorted Lists in Python?

How to Efficiently Merge Pre-Sorted Lists in Python?

DDD
Release: 2024-10-21 20:55:31
Original
327 people have browsed it

How to Efficiently Merge Pre-Sorted Lists in Python?

Merging Sorted Lists in Python

Suppose you have two pre-sorted lists of objects based on their datetime attributes. The goal is to combine them into a single sorted list. While sorting the combined list appears intuitive, there might be a more efficient approach.

Leveraging Python's Merge Function

The Python standard library provides a merge function in the heapq module, starting with Python 2.6. This function can be utilized to elegantly combine sorted lists while maintaining the initial sorting.

Example:

<code class="python">list1 = [1, 5, 8, 10, 50]
list2 = [3, 4, 29, 41, 45, 49]
from heapq import merge
result = list(merge(list1, list2))
print(result)  # [1, 3, 4, 5, 8, 10, 29, 41, 45, 49, 50]</code>
Copy after login

This approach offers improved efficiency compared to sorting the combined list, making it a more suitable choice for the given task.

The above is the detailed content of How to Efficiently Merge Pre-Sorted Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template