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)
- [3, 7, 8, 6, 1, 2]
- Syntax error
- [3, [7, 8], 6, 1, 2]
- [3, 4, 6, 7, 8]
Answer
[3, 7, 8, 6, 1, 2]
Reason —
lst = [3, 4, 6, 1, 2]
— This line initializes a list variablelst
with the values [3, 4, 6, 1, 2].lst[1:2] = [7,8]
—lst[1:2]
refers to a slice of listlst
at index 1. It replaces this slice with the values from the list[7, 8]
. Nowlst
becomes[3, 7, 8, 6, 1, 2]
.
(If we change this line tolst[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]
.)print(lst)
— This line prints the modified listlst
.
Related Questions
What will be the output of the following Python code ?
a = [10,23,56,[78, 10]] b = list(a) a[3][0] += 17 print(b)
- [10, 23, 71, [95, 10]]
- [10, 23, 56, [78, 25]]
- [10, 23, 56, [95, 10]]
- [10, 34, 71, [78, 10]]
What will be the output of the following Python code ?
lst1 = "hello" lst2 = list((x.upper(), len(x)) for x in lst1) print(lst2)
- [('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
- [('HELLO', 5)]
- [('H',5), ('E', 5), ('L',5), ('L',5), ('O', 5)]
- Syntax error
What will be the output of the following Python code snippet ?
k = [print(i) for i in my_string if i not in "aeiou"]
- prints all the vowels in my_string
- prints all the consonants in my_string
- prints all characters of my_string that aren't vowels
- prints only on executing print(k)
Which of the following is the correct expansion of list1 = [expr(i) for i in list0 if func(i)] ?
(a)
list_1 = [] for i in list_0: if func(i): list_1.append(i)
(b)
for i in list_0: if func(i): list_1.append(expr(i))
(c)
list_1 = [] for i in list_0: if func(i): list_1.append(expr(i))
(d) none of these