DEV Community

Discussion on: 5 common mistakes made by beginner Python programmers

Collapse
 
rhymes profile image
rhymes • Edited

lst is evaluated when the file is interpreted, hence it's always the same thing in memory. It's one of the gotchas of Python, you can see it here:

>>> def func(a, lst=[]):
...     print(id(lst))
...
>>> func(3)
4451985672
>>> func(4)
4451985672

As you can see lst points to the same object in memory.

If you pass an argument it will substitute the one defined at evaluation time:

>>> r = []
>>> def func(a, lst=[]):
...     lst.append(a)
...     return lst
...
>>> func(1, r)
[1]
>>> func(2, r)
[1, 2]
>>> r
[1, 2]
>>> func(4)
[4]

Notice how when I don't pass an external list as an argument, it starts using the default one.