Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

A Python beginner will expect this method to always return a list with only one element: [5]. The output is instead very different, and very surprising for a beginner:

def foo(a=[]):

    a.append(5)

    return a

>>> foo()

[5]

>>> foo()

[5, 5]

>>> foo()

[5, 5, 5]

>>> foo()

[5, 5, 5, 5]

>>> foo()

I wanted to know what is the reason for binding the default argument at function definition, and not at function execution?

1 Answer

0 votes
by (108k points)

Please be informed that this is not a design flaw, and it is not because of internals, or performance.

It originates from the fact that methods in Python are first-class objects and not just a portion of code.

A function is an object that is being estimated on its definition; default parameters are a kind of "member data" and therefore their state may change from one call to the other.

Want to get certified in Python? Register for this complete Python Training course by Intellipaat.

Browse Categories

...