# Timsort

> The sort Python uses. It finds runs already in order and merges them.

**Field:** Software Development  
**Category:** Algorithms & Data Structures  
**Also known as:** Tim Sort, TimSort

## Think of it like

Think of it like a deck that is partly in order. Keep the neat runs, then join them.

## Definition

Timsort is the sorting algorithm behind Python's sorted and list.sort. It looks for runs of items that are already in order. It makes short runs longer with insertion sort, then merges the runs, as merge sort does. It is stable and takes O(n log n) steps at worst. Tim Peters wrote it for Python in 2002, and Java uses it to sort objects.

## Example

Jack sorts 100,000 prices that were in order until 50 new ones joined the end. Timsort finds the one long run, sorts the 50 and merges them, far faster than a full sort.

## Example code

```python
>>> people = [("Emma", 9), ("Tom", 7), ("Jack", 9)]
>>> sorted(people, key=lambda p: p[1])
[('Tom', 7), ('Emma', 9), ('Jack', 9)]
```

Emma and Jack are both 9, and they keep their first order.

## Why it matters

Real data is often partly sorted already. Timsort is built to spot that and skip the work, which is why sorted is so fast in practice.

## Common mistake

Thinking Python's sort is quicksort. It is a merge sort, so it never slows to O(n²), and equal items keep their order.

## Three principles

- **Finds runs.** Runs already in order are kept.
- **Merges them.** Stable, and never worse than n log n.
- **Adaptive.** Fast on nearly sorted data.

## Related terms

- [Sorting Algorithm](https://learn.benibix.com/term/development/sorting-algorithm)
- [Merge Sort](https://learn.benibix.com/term/development/merge-sort)
- [Insertion Sort](https://learn.benibix.com/term/development/insertion-sort)
- [Python](https://learn.benibix.com/term/development/python)

---

Source: https://learn.benibix.com/term/development/timsort
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
