I am a novice in python and I did some observations that resulted in two
questions:
Question 1: Why is it that the dictionary 'b' is global over the methods in
scrips 1a and 1c and the result of 'print b' is { 'z' : 10 }? I would expect
that dictionary 'b' would be created locally in 'subtest' and that it would
stay empty in 'def test' just like in 'script 1b'. Can anybody explain the
differences?
# 1a
def test():
b = {}
subtest(b)
print b
def subtest(b):
b['z'] = 10
p = test()
result: b = { 'z' : 10 }
# 1b
def test():
b = {}
subtest(b)
print b
def subtest(b):
b = {}
b['z'] = 10
p = test()
result: b = {}
# 1c
def test():
b = {}
subtest(b)
print b
def subtest(b):
a = b
a['z'] = 10
p = test()
result: b = { 'z' : 10 }
Question 2: In script 2a list 'b' stays the same as list 'a'. In scrips 2b int
'b' doesn't stay as int 'a'. Can anybody explain these differences?
# 2a
a = [ 1, 2, 3 ]
print a
b = a
print b
print a.pop()
print a
print b
result:
[ 1, 2, 3 ]
[ 1, 2, 3 ]
3
[ 1, 2 ]
[ 1, 2 ]
# 2b
a = 1
print a
b = a
print b
a += 1
print a
print b
result:
1
1
2
1
_______________________________________________
Python-nl mailing list
Python-nl@python.org
http://mail.python.org/mailman/listinfo/python-nl