PCEP-30-02 practice question 33 of 35

Consider the function below: def func(number, result=[]): result.append(number) return result We have a classic Python problem here. The default…

Full set: 548 questions

Domain Functions and Exceptions

Consider the function below: def func(number, result=[]): result.append(number) return result We have a classic Python problem here. The default value for the result argument is a list (a mutable object). In Python, the default value of a function argument is only evaluated once. The function was called twice: func(10) func(20) Considering the above, what will be the result of the next call func(30)?
Answer options
A: []
B: [20, 30]
C: [10, 20, 30] Correct answer
D: [30]
E: 30
Correct Answer:
C. [10, 20, 30]
Explanation

In Python, a function's default arguments are evaluated only once, at the time the function is defined. The result=[] argument creates a single list object in memory when func is defined. Subsequent calls to func that do not provide a value for result will use this same list object. The first call, func(10), appends 10 to this list, making it [10]. The second call, func(20), appends 20 to the same list, resulting in [10, 20]. Therefore, the third call, func(30), appends 30 to this persistent list, and the function returns [10, 20, 30].

Why Incorrect

A. [] is incorrect because a new list is not created for each call; the same list object from the function's definition is reused and modified.
B. [20, 30] is incorrect because it ignores the modification made by the first call, func(10), which added 10 to the persistent list.
D. [30] is incorrect. This would be the result only if a new, empty list were created for this specific call, which contradicts how mutable defaults work.
E. 30 is incorrect because the function is explicitly defined to return the list object result, not the integer argument number.

References

1. Official Python Documentation: The Python Tutorial, Section 4.8.1, "Default Argument Values". This section explicitly warns about this behavior: "The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes." It provides a nearly identical example demonstrating the cumulative effect.

(Source: Python Software Foundation, The Python Tutorial, docs.python.org/3/tutorial/controlflow.html#default-argument-values)

2. University-Style Course Material/Guide: The Google Python Style Guide, a widely respected resource in both academic and professional settings, advises against this practice. Section 2.13, "Default Argument Values," states: "Do not use mutable objects as default values in the function or method definition." It explains that this can lead to unexpected sharing of the object between calls.

(Source: Google, Google Python Style Guide, google.github.io/styleguide/pyguide.html#s2.13-default-argument-values)

Scroll to Top