Python pass list as function parameter

people,

The result of the following code is [] Why isn't it ['0', '1', '2']? If I want to make psswd equal to a number in foo, what should I do?

number = ['0','1','2']
def foo(psswd):
    psswd = number[:]

if __name__ == '__main__':
    psswd = []
    foo(psswd)
    print psswd

      

+3


source to share


3 answers


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.

+1


source


You need to mutate, not rewrite, assign a slice .



psswd[:] = number[:]

      

+12


source


number = ['0','1','2']
def foo(psswd):
    psswd[:] = number  # swap the slice around here

if __name__ == '__main__':
    psswd = []
    foo(psswd)
    print psswd

      

+6


source







All Articles