Computer Science

What will be the output of the following Python code ?

lst = [3, 4, 6, 1, 2]
lst[1:2] = [7,8]
print(lst)
  1. [3, 7, 8, 6, 1, 2]
  2. Syntax error
  3. [3, [7, 8], 6, 1, 2]
  4. [3, 4, 6, 7, 8]

Linear Lists

1 Like

Answer

[3, 7, 8, 6, 1, 2]

Reason —

  1. lst = [3, 4, 6, 1, 2] — This line initializes a list variable lst with the values [3, 4, 6, 1, 2].
  2. lst[1:2] = [7,8]lst[1:2] refers to a slice of list lst at index 1. It replaces this slice with the values from the list [7, 8]. Now lst becomes [3, 7, 8, 6, 1, 2].
    (If we change this line to lst[1] = [7, 8], then output would be [3, [7, 8], 6, 1, 2] because it would replace the entire element at index 1 (i.e., 4) with [7, 8].)
  3. print(lst) — This line prints the modified list lst.

Answered By

3 Likes


Related Questions