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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

11 lines
Python 3.9+
def 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

stdout
[-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

  1. Use Python's stable sort: sorted(numbers, key=lambda x: x >= 0) to achieve the same result.
  2. 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

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.