Member-only story
Python Coding challenge — Day 240 | What is the output of the following Python Code?
2 min readAug 18, 2024
Explanation
- Default Argument Behavior:
- The default argument
x=[]
is evaluated only once when the function is defined, not each time the function is called. This means that if the default value is a mutable object like a list, it will be shared across all calls to the function.
2. First Function Call (print(func())
):
- The first time
func()
is called, the listx
is empty because the default value ([]
) is used. - Inside the function,
1
is appended to the list, sox
becomes[1]
. - The function returns this list, which is then printed, so the output is:
[1]
3. Second Function Call (print(func())
):
- The second time
func()
is called, the same listx
from the previous call is used, not a new empty list. - Again,
1
is appended to this list, sox
becomes[1, 1]
. - The function returns this list, which is then printed, so the output is:
[1, 1]
Correct Answer is: B ([1] and [1, 1])
Key Takeaways
- Mutable Default Arguments: In Python, using a mutable object (like a list or dictionary) as a default argument can lead to unexpected behavior because it persists across function calls.
- Best Practice: To avoid this, use
None
as the default value and then initialize the mutable object inside the function if needed.
Download 200 Days Python Challenge Question: https://clcoding.gumroad.com/l/vjbygj