ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
a = [1, 2, 3, 4]
a[1:3] = [9]
print(a)
b = [1, 2, 3, 4]
try:
    b[::2] = [0]
except ValueError:
    print('ValueError')
  1. A. [1, 9, 4] | [0, 2, 4]
  2. B. [1, 9, 4] | ValueError
  3. C. [1, 9, 3, 4] | ValueError
  4. D. [1, 9] | ValueError

Correct answer: B. [1, 9, 4] | ValueError

Assigning to a plain slice may change the length, so [1, 2, 3, 4] becomes [1, 9, 4]. An extended slice with step 2 needs exactly two values, so the one-item assignment raises ValueError.

More Python Programming questions

Exams that ask this topic