Python Program to Separate Even and Odd Numbers from List
even = [x for x in numbers if x % 2 == 0] and odd = [x for x in numbers if x % 2 != 0].Examples
How to Think About It
% operator. If the remainder is zero, it is even; otherwise, it is odd. Collect these numbers into two separate lists.Algorithm
Code
numbers = [1, 2, 3, 4, 5] even = [x for x in numbers if x % 2 == 0] odd = [x for x in numbers if x % 2 != 0] print("Even numbers:", even) print("Odd numbers:", odd)
Dry Run
Let's trace the list [1, 2, 3, 4, 5] through the code.
Start with the list
numbers = [1, 2, 3, 4, 5]
Check each number for evenness
1 % 2 = 1 (odd), 2 % 2 = 0 (even), 3 % 2 = 1 (odd), 4 % 2 = 0 (even), 5 % 2 = 1 (odd)
Build even and odd lists
even = [2, 4], odd = [1, 3, 5]
Print results
Even numbers: [2, 4] Odd numbers: [1, 3, 5]
| Number | Number % 2 | Even or Odd |
|---|---|---|
| 1 | 1 | Odd |
| 2 | 0 | Even |
| 3 | 1 | Odd |
| 4 | 0 | Even |
| 5 | 1 | Odd |
Why This Works
Step 1: Check remainder with modulo
Using % 2 gives the remainder when dividing by 2, which tells if a number is even or odd.
Step 2: Separate numbers into lists
Numbers with remainder 0 go into the even list; others go into the odd list.
Step 3: Use list comprehensions
List comprehensions make it easy and concise to filter numbers based on the condition.
Alternative Approaches
numbers = [1, 2, 3, 4, 5] even = [] odd = [] for num in numbers: if num % 2 == 0: even.append(num) else: odd.append(num) print("Even numbers:", even) print("Odd numbers:", odd)
numbers = [1, 2, 3, 4, 5] even = list(filter(lambda x: x % 2 == 0, numbers)) odd = list(filter(lambda x: x % 2 != 0, numbers)) print("Even numbers:", even) print("Odd numbers:", odd)
Complexity: O(n) time, O(n) space
Time Complexity
The program checks each number once, so time grows linearly with the list size.
Space Complexity
Two new lists are created to store even and odd numbers, so space also grows linearly.
Which Approach is Fastest?
List comprehensions and filter with lambda have similar speed; for loop is slightly slower but clearer for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List Comprehension | O(n) | O(n) | Concise and fast code |
| For Loop with Append | O(n) | O(n) | Clear and beginner-friendly |
| Filter with Lambda | O(n) | O(n) | Functional programming style |
% 2 to check evenness and instead using incorrect conditions.