Why Changing a List Inside a Python Function Alters the Original Value
This article explains the difference between immutable and mutable objects in Python, using clear examples to show why modifying a list parameter inside a function changes the original variable while altering a number does not, helping beginners master function arguments and avoid common interview pitfalls.
Yesterday in a Python learning group a newcomer asked a basic question about formal (parameter) and actual arguments in Python functions. Although simple, many beginners get confused, so I’ll clarify the usage of arguments in Python.
First, consider an immutable object example.
In this function the output is 6, not 7, because numbers (as well as strings and tuples) are immutable. The parameter’s value does not affect the external argument’s value; they refer to different objects.
Next, consider a mutable object example using a list.
Here the function returns [2, 1] instead of [1, 2] because lists are mutable. Modifying the list inside the function changes the original argument.
This type of question often appears in interviews to test Python fundamentals.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
