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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Might need a little more explanation than this - then again, this is no doubt a dupe.
how does python determine when to rebind and when to mutate?
It rebinds when you assign to a bare name (e.g. foo =). Every other assignment operation is (usually) mutation.
Yeah! got it. But how can i replace all values of x with y.should i manually loop through each element?
@ignacio: great!...but one more silly question.slice assign just shallow copies..so how will i deep copy?
|
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]

6 Comments

How come X suddenly becomes local variable.It should still be the reference even after assigning rit?
x is a local variable inside the functions because it is used in the arguments (inside the function header).
It is a reference. Bit in func this reference is reassigned to point to a new object.
Thank you , i understand it a little bit better now. So , if I want the first function to change x to y , i just have to do x[:] = y , right ?
@geekid you just need to do a shallw copy using slice assign like this x=y[:]
|

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.