r/PythonProjects2 • • Apr 09 '26

Guess the output

Post image
32 Upvotes

17 comments sorted by

8

u/ParticularLook5927 Apr 09 '26

Answer: B) [1], [1, 1]

This happens because default mutable arguments (like lists) are shared across function calls.

The list x=[] is created only once when the function is defined, not every time the function is called.

So: First call → [1] Second call → same list gets another 1 → [1, 1]

To fix this, use:

def foo(x=None):

if x is None:
    x = []

x.append(1)

return x

This way, a new list is created every time.

3

u/L_Shiro Apr 09 '26

in the example you shared, how it will create new one each time? if x = is empty, it will create

the second time the list exist and not none, so it becomes x = [ 1, 1]

maybe i don't get it right?

→ More replies (4)

3

u/Wild-Release-719 Apr 10 '26

I'm happy I rapidly switched languages and didn't stick to Python as I did with Scratch

→ More replies (1)

2

u/jpgoldberg Apr 09 '26 edited Apr 11 '26

The behavior of mutable default arguments in Python is among the most evil things about language.

I know that beginners have a lot of different tools to learn, and learning how to use an IDE if you have never used a programming editor is an additional burden, but I still think that people should learn how to use some linter or other relatively early.

→ More replies (3)

2

u/Leviterion_HU Apr 10 '26

A) [1, 1] bacause of mutable default arguments