Even Filter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a list of integers, return a new list containing only the even numbers in their original order.
Only the even ones survive.
Example 1
Input:
nums = [1,2,3,4,5,6]
Output:
[2,4,6]
Example 2
Input:
nums = [1,3,5]
Output:
[]
Worked solution and explanation
Why this problem exists in real interviews
Filter-a-list-by-predicate is the warm-up interviewers open with to check Python fluency before the harder problem. The right answer is one expression; the wrong answer is a loop with an accumulator list and an if. What they actually grade is whether you reach for a list comprehension or filter(), whether you preserve input order, and whether you avoid mutating the input.
Break down the requirements
Step 1: Use a list comprehension with a predicate
[x for x in nums if x % 2 == 0] is the Pythonic one-liner. It preserves input order by construction (iteration is left to right), allocates the result once, and runs the predicate in the interpreter loop without the overhead of a named function.
Step 2: Use the modulo test, not bitwise tricks
x % 2 == 0 reads as English and handles negative integers and zero correctly (0 % 2 == 0, -2 % 2 == 0 in Python). Bitwise x & 1 == 0 also works but sacrifices readability for zero speedup on interview-sized inputs.
Step 3: Return a new list, never mutate the input
The spec says 'return a new list,' so produce a fresh object. A list comprehension already does this. Using nums.remove(x) in a loop would mutate and also be O(n^2) due to repeated shifts; both are wrong.
The solution
def even_filter(nums: list) -> list:
return [x for x in nums if x % 2 == 0]Common follow-up questions
- How would you split nums into (evens, odds) in a single pass? (one loop with two appends, or two comprehensions if readability matters more than a single scan; discuss the tradeoff.)
- What changes if nums is a generator that cannot be iterated twice? (a single comprehension consumes the generator correctly; calling len() on it first would exhaust it. Discuss defensive list() if needed.)
- How would you parallelize this for a huge array on a multicore machine? (numpy vectorization (nums[nums % 2 == 0]) or multiprocessing.Pool with chunks; note that the GIL blocks thread-level parallelism for pure-Python predicates.)