3

I'm having trouble understanding the odd behaviour in python functions if i pass in a list. I made the following functions:

def func(x):
    y = [4, 5, 6]
    x = y

def funcsecond(x):
    y = [4, 5, 6]
    x[1] = y[1]

x = [1, 2, 3]

When i call func(x) and then print out x , it prints out [1, 2, 3], just the way x was before, it doesnt assign the list y to x. However, if i call funcsecond(x), it assigns 5 to the second position of x. Why is that so? When i assign the whole list, it doesn't do anything, but when i assign only one element, it changes the list i originally called it with. Thank you very much and i hope you understand what im intending to say , i'm having a hard time expressing myself in English.

stensootla
  • 13,945
  • 9
  • 45
  • 68

2 Answers2

9

The former rebinds the name, the latter mutates the object. Changes to the name only exist in local scope, whereas a mutated object remains mutated after the scope is exited.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

this is happening beacuse x points to a object which is mutable.

def func(x): # here x is a local variable which refers to the object[1,2,3]
    y = [4, 5, 6]
    x = y  #now the local variable x refers to the object [4,5,6]

def funcsecond(x): # here x is a local variable which refers to the object[1,2,3]
    y = [4, 5, 6]
    x[1] = y[1]  # it means [1,2,3][1]=5 , means you changed the object x was pointing to

x = [1, 2, 3]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504