A generator and a comprehension in one line — Aptitude
A generator and a comprehension in one line: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this Python program print?
nums = [1, 2, 3, 4, 5, 6]
print(sum(n for n in nums if n % 2 == 0), [n * 2 for n in nums][2])Options
- 9 6
- 12 3
- 12 6
- 21 6
Show the answer and the worked solution
Correct answer: C. 12 6
Worked solution
- The generator keeps the even numbers 2, 4 and 6, and sum returns 2 + 4 + 6 = 12.
- The comprehension doubles every element, giving [2, 4, 6, 8, 10, 12].
- Index 2 of that list is its third element, 6, so the line prints 12 6.
Answer: 12 6.
The idea
A filtered generator inside sum is the idiomatic conditional total, and a comprehension produces a full list that can be indexed like any other. Zero-based indexing is what makes the second value 6 rather than 4.
Shortcut. The evens add to 2 + 4 + 6 = 12, and index 2 of the doubled list is double the third element, 3 × 2 = 6.
Common trap. "21 6" sums every number in the list, overlooking the if n % 2 == 0 filter inside the generator.
All Programming Fundamentals questions · placement mock tests