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.
Python code
20 linesdef 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
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
- Use list comprehensions to create each sublist directly: `less = [x for x in lst if x < pivot]`.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.