How to Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

20 lines
Python 3.9+
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__":
    data = [3, 9, 5, 2, 5, 7, 1, 5]
    pivot = 5
    result = partition_list(data, pivot)
    print(f"Original: {data}")
    print(f"Pivot: {pivot}")
    print(f"Partitioned: {result}")

Output

stdout
Original: [3, 9, 5, 2, 5, 7, 1, 5]
Pivot: 5
Partitioned: [3, 2, 1, 5, 5, 5, 9, 7]

How it works

The function iterates through the list once and appends each element to one of three separate lists: less, equal, or greater. This approach is stable because equal elements keep their original relative order and the concatenation preserves the order of the less and greater groups. At the end, the three lists are combined using the + operator, which creates a new list containing all elements in the desired partitioned order. The algorithm runs in O(n) time, where n is the list length, and uses O(n) extra space for the three sublists.

Common mistakes

  • Forgetting to handle equal elements, causing them to be placed in an unintended group.
  • Modifying the original list in place without creating copies, which can lead to unexpected side effects.
  • Confusing the pivot value with its index when using list comprehensions.

Variations

  1. Use list comprehensions to create each sublist directly: `less = [x for x in lst if x < pivot]`.
  2. Use `filter()` with a custom predicate for each condition, though it is less readable.

Real-world use cases

  • Rearranging records in a dataset so that all values below a threshold come first, e.g., separating low-risk transactions for manual review.
  • Implementing a stable partition step for algorithms like quicksort, where order preservation matters.
  • Grouping user input based on a scoring threshold in a recommendation engine before further processing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.