Member-only story

Explanation

  1. 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 list x is empty because the default value ([]) is used.
  • Inside the function, 1 is appended to the list, so x 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 list x from the previous call is used, not a new empty list.
  • Again, 1 is appended to this list, so x 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

--

--

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