Default Argument Question

P

Paulo J. Matos

Hi all,

Going through the tutorial brought up a question. Consider the functions:

def f(a, L=[]):
L.append(a)
return L

print f(3)
print f(9)
print f(7)

def f1(i = 0):
i = i + 1
print i

f1()
f1()
f1()
f1()

Since the f accumulates the values in L, I was expecting to see i
printing 1,2,3,4 but this doesn't happen.
Can someone please explain why and what is going on beneath the veil?

Cheers,
 
B

Bruno Desthuilliers

Paulo J. Matos a écrit :
Hi all,

Going through the tutorial brought up a question. Consider the functions:

def f(a, L=[]):
L.append(a)
return L

print f(3)
print f(9)
print f(7)

def f1(i = 0):
i = i + 1
print i

f1()
f1()
f1()
f1()

Since the f accumulates the values in L, I was expecting to see i
printing 1,2,3,4 but this doesn't happen.
Can someone please explain why and what is going on beneath the veil?

In the first case, you are mutating L. In the second, you are rebinding
the local name i. IOW, you are comparing oranges and apples. The
corresponding code using a list would be:
.... alist = alist + [arg]
.... print alist
....

And it behaves just like your f1 function:
>>> f2(1) [1]
>>> f2(1) [1]
>>> f2(1) [1]
>>> f2(1) [1]
>>>


But anyway: you just couldn't mutate i in f1, since integers are
immutables...

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top