Question:hard

What possible output(s) from the given options will NOT be displayed when the following code is executed? Also, mention, for how many iterations the for loop in the given code will run?

import random
a = [1,2,3,4,5,6]
for i in range(4):
    j = random.randrange(i,5)
    print(a[j],end='-')
print()

Show Hint

In pass i, randrange(i,5) gives j from i to 4, so a[j] lies between i+1 and 5. The loop runs 4 times.
Updated On: Oct 20, 2026
  • 3-4-5-4-
  • 2-2-4-5-
  • 4-3-3-5-
  • 5-1-2-4-
Show Solution

The Correct Option is D

Solution and Explanation

Step 1: Start from the pattern of the output:
Every option has four numbers, and the code prints one number per iteration.
This matches the four passes of range(4), which gives i = 0, 1, 2, 3.

Step 2: Find the smallest value allowed at each position:
The smallest j in pass i is i itself, so the smallest printed value is a[i] = i + 1.
The largest j is always 4, so the largest printed value is a[4] = 5.
So the 1st value is from 1 to 5, the 2nd from 2 to 5, the 3rd from 3 to 5, and the 4th from 4 to 5.

Step 3: Check which option breaks a limit:
Option 1: 3, 4, 5, 4 all stay inside the limits.
Option 2: 2, 2, 4, 5 all stay inside the limits.
Option 3: 4, 3, 3, 5 all stay inside the limits.
Option 4: the 2nd value is 1, but the lowest allowed there is 2. The 3rd value is 2, but the lowest allowed there is 3. So this option breaks the rule.

Final Answer:
Option 4 (5-1-2-4-) cannot appear, and the loop runs 4 times.
Was this answer helpful?
0