AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumpythoncomprehensions

~90s

A generator and a comprehension in one line

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])
Show the answer and the worked solution

Correct answer: C.

12 6

Worked solution

  1. The generator keeps the even numbers 2, 4 and 6, and sum returns 2 + 4 + 6 = 12.
  2. The comprehension doubles every element, giving [2, 4, 6, 8, 10, 12].
  3. 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.

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.

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

  1. 9 6
  2. 12 3
  3. 12 6
  4. 21 6
Show the answer and the worked solution

Correct answer: C. 12 6

Worked solution

  1. The generator keeps the even numbers 2, 4 and 6, and sum returns 2 + 4 + 6 = 12.
  2. The comprehension doubles every element, giving [2, 4, 6, 8, 10, 12].
  3. 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