KnowledgeBoat Logo

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)
  1. [10, 23, 71, [95, 10]]
  2. [10, 23, 56, [78, 25]]
  3. [10, 23, 56, [95, 10]]
  4. [10, 34, 71, [78, 10]]

Linear Lists

5 Likes

Answer

[10, 23, 56, [95, 10]]

Reason —

  1. a = [10, 23, 56, [78, 10]] — This creates a nested list a.
  2. b = list(a) — This creates a shallow copy of a and assigns it to b. The list b references to the same objects as a.
  3. a[3][0] += 17a[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.
  4. print(b) — This prints the contents of list b. Since b is a shallow copy of a, any changes made to the nested list within a will also reflect in b. Therefore, when we print b, we'll see the modified value [95, 10].

Answered By

3 Likes


Related Questions