4

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

3 Answers 3

12

You need to mutate instead of rebinding, with slice-assigning.

psswd[:] = number[:]
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

1

Your code:

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

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

psswd = number[:] rebinds local variable psswd with a new list.

I.e., when you do foo(psswd), function foo is called, and local variable passwd inside it is created which points to the global list under the same name.

When you do psswd = <something> inside foo function, this <something> is created/got and local name psswd is made to point to it. Global variable psswd still 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 calls psswd.__setitem__ method, thus the object which is referenced by local name psswd is modified.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.