Member-only story
Python Coding challenge — Day 241 | What is the output of the following Python Code?
1 min readAug 24, 2024
a = [1, 2, 3]
b = a
a.append(4)
print(b)
Solution and Explanation
a = [1, 2, 3]
:
This line creates a lista
with elements[1, 2, 3]
.b = a
:
Here,b
is not a new list but a reference to the same list object thata
refers to. In Python, variables that hold lists (and other mutable objects) actually hold references to the memory location where the list is stored. So,b
now refers to the same list asa
.a.append(4)
:
This line adds the element4
to the end of the lista
. Sincea
andb
refer to the same list, this modification affects botha
andb
.print(b)
:
Sinceb
refers to the same list asa
, the output will show the modified list[1, 2, 3, 4]
.
Final Output:
[1, 2, 3, 4]
The key concept here is that a
and b
are references to the same list in memory, so changes to the list via one variable are reflected in the other.