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.
Python code
23 linesdef 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
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
- Use a two-pointer in-place approach: `left` searches for odds, `right` for evens, swap them
- 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
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.