Filter even numbers with a Python list comprehension, and compare it with a for-loop and filter(). Learn comprehension syntax with live tests.
The problem
Return the even numbers from nums using a single list comprehension.
Examples
Example 1
Input
evens([1, 2, 3, 4, 5, 6])
Expected output
[2, 4, 6]
Example 2
Input
evens([1, 3])
Expected output
[]
+ 2 hidden tests on Submit — 0 and negatives.
Edge cases to ask about
- Zero
- Negative numbers
- Empty
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| List comprehension | O(n) | O(n) | [expr for x in it if cond] |
Walkthrough of the optimal approach (try it yourself first)
[x for x in nums if x % 2 == 0]. A comprehension is not just shorter — it avoids the repeated .append attribute lookup, so it is usually faster than the equivalent loop. Use a generator expression (x for …) when you only need to iterate once.
Complexity: O(n) time, O(n) space. One pass; the result can hold every element.
Reveal the reference solution
def evens(nums): return [x for x in nums if x % 2 == 0]
Follow-ups interviewers ask
- Square the evens in the same comprehension.
- When would you use a generator expression instead?
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of List Comprehension: Filter Even Numbers in Python?
The optimal solution runs in O(n) time and O(n) auxiliary space. One pass; the result can hold every element.
What follow-up questions do interviewers ask about List Comprehension: Filter Even Numbers?
Square the evens in the same comprehension. When would you use a generator expression instead?
