Computer Science
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]]
Linear Lists
5 Likes
Answer
[10, 23, 56, [95, 10]]
Reason —
a = [10, 23, 56, [78, 10]]
— This creates a nested lista
.b = list(a)
— This creates a shallow copy ofa
and assigns it tob
. The listb
references to the same objects asa
.a[3][0] += 17
—a[3]
accesses the sublist at index 3, i.e., [78, 10], and[0]
further accesses the first element of that sublist, i.e., 78. Then, it adds 17 to 78, changing it to 95.print(b)
— This prints the contents of listb
. Sinceb
is a shallow copy ofa
, any changes made to the nested list withina
will also reflect inb
. Therefore, when we printb
, we'll see the modified value [95, 10].
Answered By
3 Likes
Related Questions
What is a nested list ?
Is Ragged list a nested list ?
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 ?
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]