Animations
Even or Odd — Visual Walkthrough
Watch how Python separates a mixed array into even and odd numbers using the modulo operator.
Even or Odd
Array: [3, 8, 1, 6, 4, 7, 2, 9, 5, 10]
Loop through every number. If num % 2 == 0 it is even — goes to the even list. Otherwise it is odd — goes to the odd list.
Even / Oddseparation · O(n)
even → blueodd → orange
Input array
3
[0]8
[1]1
[2]6
[3]4
[4]7
[5]2
[6]9
[7]5
[8]10
[9]even [ ]0 items
empty
odd [ ]0 items
empty
even_odd.py
def separate_even_odd(arr):
even, odd = [], []
for num in arr:
# pick current number
if num % 2 == 0:
even.append(num) # even bucket
else:
odd.append(num) # odd bucket
return even, odd
Call separate_even_odd([3,8,1,6,4,7,2,9,5,10])
step 0/33
0%
How it works
def separate_even_odd(arr):
even, odd = [], []
for num in arr:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
return even, oddnum % 2 gives the remainder after dividing by 2. Even numbers always have remainder 0. Odd numbers always have remainder 1.
The order of the original array is preserved inside each bucket. [3, 8, 1, 6, 4] gives even = [8, 6, 4] and odd = [3, 1] — same relative order as the original.
Complexity
| Time | Space | |
|---|---|---|
| This approach | O(n) | O(n) |
One pass through the array. Two output lists that together hold all n elements.