Segregate Negative Numbers Before Positives in Python
Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.
Python code
11 linesdef segregate_negatives(numbers):
"""Segregate negatives before positives without altering relative order."""
negatives = [n for n in numbers if n < 0]
positives = [n for n in numbers if n >= 0]
return negatives + positives
if __name__ == "__main__":
sample = [3, -1, 4, -5, 2, -9, 0]
result = segregate_negatives(sample)
print(result)
Output
[-1, -5, -9, 3, 4, 2, 0]
How it works
The function uses two list comprehensions to partition the input: one for negatives and one for non-negatives. Since list comprehensions iterate the original sequence in order, the relative order of elements within each partition is preserved automatically. Concatenating the two lists with + places all negatives first, followed by the positives and zeros. This approach is stable, simple, and runs in O(n) time with O(n) extra space for the output lists.
Common mistakes
- Using a custom sort with a key function that is not stable, which can alter relative order.
- Modifying the list in-place with append/pop while iterating, which can skip elements.
- Forgetting that zero should be treated as non-negative (>= 0).
Variations
- Use Python's stable sort: sorted(numbers, key=lambda x: x >= 0) to achieve the same result.
- Use a two-pointer in-place partition when relative order is not required.
Real-world use cases
- Reordering a queue of tasks so that priority negative-priority items are processed first.
- Partitioning sensor readings into anomaly (negative) and normal (positive/zero) groups before analysis.
- Preparing data for a financial report by separating credits (negative) from debits (positive) preserving entry order.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.