Python trick to be careful of!


#1

Let’s analyze the output of the following dummy function,

def dummy(a, b=[]):
for i in range(a):
b.append(i)
print(b)

  1. dummy(2) prints [0,1]

  2. dummy(4, b=[1,2] ) prints [1,2,0,1,2,3]

  3. dummy (4) prints [0,1,0,1,2,3],

Here it seems like it should print [0,1,2,3] but the result is not as expected. When we executed dummy(2) (above in the step 1) the second keyword variable was not passed but in the function’s definition b is an empty list. So when the dummy(2) executed, b was pointing to an empty list (list object) and appended 0 and 1 to it, thus it became [0,1].

At step 2 we passed b as [1,2] so in the function the append happened to the [1,2] list and returned [1,2,0,1,2,3].

Next, while executing the third one we are again not passing the b and b is already pointing to the list object created in the step1(which changed from an empty list to [0,1]) and hence the function will append the values in the same pointed list([0,1] ) during execution and returned [0,1,0,1,2,3]