-1

This is my code:

def toto(liste=[]):
    print(id(liste))
    liste.append("coucou")
    print(id(liste))
    return liste
    
print(toto())
print(toto())
print(toto([]))
print(toto([]))

And the result in the console:

63335800
63335800
['coucou']
63335800
63335800
['coucou', 'coucou']
60547280
60547280
['coucou']
60547280
60547280
['coucou']

Why this difference? Why does Python use the same object as a local variable (same identifier) and why don't we get the same result depending on whether or not we put the empty list as an input parameter?

  • To add to the duplicate for the specific case: in the later two examples - they actually aren't the same object. As soon as first `print(toto([]))` is completed, you lose all references to that list so it can be garbage collected and the same id can reused for a brand new list. – matszwecja May 09 '22 at 13:59

0 Answers0