Question:

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
collegedunia
Verified By Collegedunia

The Correct Option is D

Solution and Explanation

Step 1: Count the iterations:
The loop is for i in range(4).
range(4) gives 0, 1, 2, 3. So the loop runs 4 times.

Step 2: Find the values each iteration can print:
random.randrange(i, 5) gives a whole number j from i up to 4 (5 is not included).
The list is a = [1, 2, 3, 4, 5, 6], so a[j] = j + 1.
Iteration 1 (i = 0): j is 0 to 4, so the printed value is 1 to 5.
Iteration 2 (i = 1): j is 1 to 4, so the printed value is 2 to 5.
Iteration 3 (i = 2): j is 2 to 4, so the printed value is 3 to 5.
Iteration 4 (i = 3): j is 3 to 4, so the printed value is 4 or 5.

Step 3: Test each option against these ranges:
Option 1, 3-4-5-4-: 3 is in 1-5, 4 is in 2-5, 5 is in 3-5, 4 is in 4-5. Possible.
Option 2, 2-2-4-5-: 2 is in 1-5, 2 is in 2-5, 4 is in 3-5, 5 is in 4-5. Possible.
Option 3, 4-3-3-5-: 4 is in 1-5, 3 is in 2-5, 3 is in 3-5, 5 is in 4-5. Possible.
Option 4, 5-1-2-4-: the second value 1 is not in 2-5, and the third value 2 is not in 3-5. Not possible.

Final Answer:
The output 5-1-2-4- will NOT be displayed (option 4). The for loop runs 4 iterations.
Was this answer helpful?
0
0