functions, list, default parameters
Sean Choi
gnemnk at gmail.com
Thu Oct 21 17:36:32 EDT 2010
I found two similar questions in the mailing list, but I didn't understand
the explanations.
I ran this code on Ubuntu 10.04 with Python 2.6.5.
Why do the functions g and gggg behave differently? If calls gggg(3) and
g(3) both exit their functions in the same state, why do they not enter in
the same state when I call gggg(4) and g(4)?
# ---------------------------------------------------------------------- my
code:
def gggg(a, L=[]):
print "enter function"
print "a = ", a, "and L = ", L
if L == []:
print "hey, L is empty"
L = []
L.append(a)
print "after append, L = ", L
return L
def g(a, L=[]):
print "enter function"
print "a = ", a, "and L = ", L
if L == []:
print "hey, L is empty"
L.append(a)
print "after append, L = ", L
return L
print gggg(3)
print gggg(4)
print gggg(7)
print g(3)
print g(4)
print g(7)
# ---------------------------------------------------------------------- my
output:
-------------------gggg calls
enter function
a = 3 and L = []
hey, L is empty
after append, L = [3]
[3]
enter function
a = 4 and L = []
hey, L is empty
after append, L = [4]
[4]
enter function
a = 7 and L = []
hey, L is empty
after append, L = [7]
[7]
-------------------g calls
enter function
a = 3 and L = []
hey, L is empty
after append, L = [3]
[3]
enter function
a = 4 and L = [3]
after append, L = [3, 4]
[3, 4]
enter function
a = 7 and L = [3, 4]
after append, L = [3, 4, 7]
[3, 4, 7]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101021/e5eb36c3/attachment.html>
More information about the Python-list
mailing list