Question 29: Understanding Mutable Default Arguments in Python

This question tests your knowledge of how Python handles mutable default arguments in function definitions.

It explores the behavior of default arguments, particularly when the default value is a mutable object like a list.

Understanding this concept is crucial to avoid unintended side effects in your Python programs.

Question: Mutable Default Arguments in Python

What will be the output of the following Python code snippet?

def func(x=[]):
    x.append(len(x))
    return x

print(func())
print(func())
















Answer: C

Explanation:

The default argument x=[] is evaluated only once, so the same list is used in each call to func.

When the function is called the first time, it appends 0 to the list. When called again, it appends 1 to the same list, resulting in [0, 1].

Leave a Reply