How to Sort Array by Parity (Even Before Odd) in Python

Rearrange an array so all even numbers appear before all odd numbers using a simple two-list partition approach.

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

Python code

23 lines
Python 3.9+
def sort_array_by_parity(nums):
    """
    Rearrange the array so that all even integers come first,
    followed by all odd integers. The order within even and odd
    groups is not required to be sorted.
    """
    even = []
    odd = []
    
    for num in nums:
        if num % 2 == 0:
            even.append(num)
        else:
            odd.append(num)
    
    return even + odd

if __name__ == "__main__":
    # Example usage
    arr = [3, 1, 2, 4, 6, 5, 7]
    result = sort_array_by_parity(arr)
    print(f"Original: {arr}")
    print(f"After sorting by parity: {result}")

Output

stdout
Original: [3, 1, 2, 4, 6, 5, 7]
After sorting by parity: [2, 4, 6, 3, 1, 5, 7]

How it works

This solution iterates through the input list once, appending each number to one of two accumulator lists based on whether num % 2 == 0. The even list is concatenated with the odd list using the + operator to produce the final result. This runs in O(n) time and O(n) space, where n is the length of the input array. The approach is straightforward and preserves the original relative order within each parity group.

Common mistakes

  • Using `num % 2 == 1` for odd detection, which fails for negative numbers; use `!= 0` instead
  • Modifying the input list with `pop()` while iterating, which causes skipped elements
  • Attempting to sort numerically instead of only separating parity groups

Variations

  1. Use a two-pointer in-place approach: `left` searches for odds, `right` for evens, swap them
  2. Use a list comprehension: `[n for n in nums if n % 2 == 0] + [n for n in nums if n % 2 != 0]`

Real-world use cases

  • Partitioning transaction records by account type (e.g., credit vs. debit) before batch processing.
  • Separating log entries by severity level (error vs. info) for downstream alerting pipelines.
  • Grouping sensor readings into valid vs. anomalous buckets before anomaly detection models run.

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.