0
def demo(v,l=[]):
     l.append(v)
     return l
l1=demo(10) #output [10]
l2=demo(21,[])
l3=demo('a')
print('List 1: ', l1) #output=[10]
print('List 2: ', l2) #output=[21]
print('List 3: ', l3) #output=[10,'a']

How is the list updating even if I am using different objects for the function?

jmd_dk
  • 12,125
  • 9
  • 63
  • 94

1 Answers1

0

Default arguments of functions (here l=[]) are not re-created upon function calls, but only created once when the function is defined. Thus, it really is the same object l that is referred to for all calls to demo().

This is usually not the behavior one wants. The typical way to get around it is to use an immutable object as the default value, often None:

def demo(v, l=None):
    if l is None:
        l = []  # Create new empty list
    l.append(v)
    return l
jmd_dk
  • 12,125
  • 9
  • 63
  • 94