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
nos
  • 19,875
  • 27
  • 98
  • 134

3 Answers3

12

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

psswd[:] = number[:]
Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
6
number = ['0','1','2']
def foo(psswd):
    psswd[:] = number  # swap the slice around here

if __name__ == '__main__':
    psswd = []
    foo(psswd)
    print psswd
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
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.

warvariuc
  • 57,116
  • 41
  • 173
  • 227