Separate Evens and Odds into Two Lists in Python
Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.
Python code
15 linesdef separate_evens_odds(numbers):
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens, odds
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens, odds = separate_evens_odds(nums)
print(f"Evens: {evens}")
print(f"Odds: {odds}")
Output
Evens: [2, 4, 6, 8, 10]
Odds: [1, 3, 5, 7, 9]
How it works
The function iterates over each number in the input list. The % (modulo) operator returns the remainder after division; if num % 2 is 0, the number divides evenly by 2 and is even, so it's appended to evens, otherwise it goes to odds. Appending to lists is O(1) on average, making this approach linear in time complexity O(n). Returning a tuple (evens, odds) lets you unpack the two lists directly in the caller.
Common mistakes
- Using `if num % 2:` to check for even (that catches odd numbers instead)
- Forgetting that 0 is even and should go to the evens list
- Mutating the input list instead of creating new lists
Variations
- Use list comprehensions: `evens = [n for n in numbers if n % 2 == 0]` and `odds = [n for n in numbers if n % 2 != 0]`
- Use `filter` with lambda for a functional approach
Real-world use cases
- Segmenting transaction amounts into even/odd buckets for fraud detection analysis.
- Partitioning sensor readings like channel IDs for load-balanced processing.
- Grouping test case indices into separate queues for parallel execution.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.