Q.What will be the output of the following code segment:
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])
The condition i % 2 == 0 filters on the index, not the value: indices 0, 2, 4, 6, 8 are selected, and since myList holds 1-10 in order, the values printed are 1, 3, 5, 7, 9.
The idea. range(0, len(myList)) generates the index sequence 0…9; inside the loop, myList[i] accesses by index. The whole question hinges on reading if i % 2 == 0 correctly — it tests whether the position is even, while the values at even positions happen to be the odd numbers (because the list starts at 1). That inversion is deliberate.
Dry run:
| i | i % 2 == 0? | myList[i] | printed? |
|---|---|---|---|
| 0 | Yes | 1 | 1 |
| 1 | No | 2 | — |
| 2 | Yes | 3 | 3 |
| 3 | No | 4 | — |
| 4 | Yes | 5 | 5 |
| 5 | No | 6 | — |
| 6 | Yes | 7 | 7 |
| 7 | No | 8 | — |
| 8 | Yes | 9 | 9 |
| 9 | No | 10 | — |
Expected output:
1
3
5
7
9
Each value appears on its own line because every print() call ends with a newline by default.
Writing "2, 4, 6, 8, 10" is the classic wrong answer — that would require the condition myList[i] % 2 == 0 (testing the element). Always check whether a condition is applied to the index or to the value it selects.
The code prints 1, 3, 5, 7, 9 — one per line — because it outputs the elements sitting at the even indices 0, 2, 4, 6 and 8.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.