Member-only story

Python Coding challenge — Day 241 | What is the output of the following Python Code?

Python Coding
1 min readAug 24, 2024

--

a = [1, 2, 3]
b = a
a.append(4)
print(b)

Solution and Explanation

  1. a = [1, 2, 3]:
    This line creates a list a with elements [1, 2, 3].
  2. b = a:
    Here, b is not a new list but a reference to the same list object that a 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 as a.
  3. a.append(4):
    This line adds the element 4 to the end of the list a. Since a and b refer to the same list, this modification affects both a and b.
  4. print(b):
    Since b refers to the same list as a, 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.

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet