folks,
The result of the following code is []
Why is it not [‘0′,’1′,’2’]? If I want to make psswd equal to number in the function foo, what should I do?
number = ['0','1','2']
def foo(psswd):
psswd = number[:]
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
Your code:
psswd = number[:]rebinds local variablepsswdwith a new list.I.e., when you do
foo(psswd), functionfoois called, and local variablepasswdinside it is created which points to the global list under the same name.When you do
psswd = <something>insidefoofunction, this<something>is created/got and local namepsswdis made to point to it. Global variablepsswdstill points to the old value.If you want to change the object itself, not the local name, you must use this object’s methods.
psswd[:] = <smething>actually callspsswd.__setitem__method, thus the object which is referenced by local namepsswdis modified.