Python pass list as function parameter
Your code:
number = ['0','1','2']
def foo(psswd):
psswd = number[:]
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
psswd = number[:]
restores a local variable psswd
with a new list.
Ie, when you execute foo(psswd)
, a function is called foo
and inside of it a local variable is created passwd
that points to a global list of the same name.
When you execute psswd = <something>
internally foo
, this one <something>
is created / retrieved and the local name psswd
is made to point to it. The global variable psswd
still points to the old value.
If you want to change the object itself and not the local name, you must use these methods of the object. psswd[:] = <smething>
is actually calling the method psswd.__setitem__
, so the object being referenced by the local name psswd
changes.
source to share