PCEP-30-02 · Question #160
What is the expected output of the following code? ``python def func(data): for d in data[::2]: yield d for x in func('abcdef'): print(x, end='') ``
The correct answer is A. ace. Option A is correct because data[::2] slices the string 'abcdef' with a step of 2, selecting characters at indices 0, 2, and 4 - which are 'a', 'c', and 'e' - and yield turns func into a generator that produces each one, printed without a separator via end=''. B (bdf) is wrong…
Question
def func(data):
for d in data[::2]:
yield d
for x in func('abcdef'):
print(x, end='')
Options
- Aace
- Bbdf
- Cabcdef
- DAn empty line.
How the community answered
(31 responses)- A77% (24)
- B6% (2)
- C13% (4)
- D3% (1)
Explanation
Option A is correct because data[::2] slices the string 'abcdef' with a step of 2, selecting characters at indices 0, 2, and 4 - which are 'a', 'c', and 'e' - and yield turns func into a generator that produces each one, printed without a separator via end=''.
B (bdf) is wrong because that result requires data[1::2] (starting at index 1, the odd-indexed characters); the step-2 slice here starts at index 0 by default.
C (abcdef) is wrong because that would require no slicing at all (or data[::1]); the [::2] step skips every other character.
D (empty line) is wrong because the generator does produce values - yield inside a for loop over a non-empty slice will always yield at least one element when the iterable has content.
Memory tip: Read [::2] as "every 2nd item starting from the beginning (index 0)" - it always picks even-indexed positions (0, 2, 4…), giving you the odd-positioned characters in everyday 1-based counting.
Community Discussion
No community discussion yet for this question.