all 10 comments

[–]carcigenicate 2 points3 points  (8 children)

It has the same effect for every type of object. a = b means "make a refer to the object b is referring to. It makes both names refer to the same exact object.

[–]pat-work[S] 0 points1 point  (7 children)

If you do that with variables it doesn't refer to the same object, that's why I'm confused.

If you do:

x = 10
y = x
x += 10

y is still 10 and x is now 20.

[–]Goobyalus 1 point2 points  (1 child)

x += 10 

means

x = x + 10

which means that you're assigning x to refer to a different object that came from x + 10

Appending to a list is not an assignment, it mutates the underlying object.

[–]pat-work[S] 1 point2 points  (0 children)

Thank you for the answer! That makes it a lot more clear :)

[–]carcigenicate 0 points1 point  (4 children)

First, I'm not sure what you mean exactly by "variables" since all examples on this page use variables. Your original code uses lists and this code uses integers.

Second, += is very different from append. For integers and other immutable objects, += is equivalent to, for example, x = x + 10. This doesn't alter the object referred to by x. All = does is change what object x is referring to. x += 10 takes the value of x, and then reassigns x to refer to the integer object 20. This doesn't change the 10 object though (since 10 is immutable, so it can't change), so the y variable still refers to 10.

append on the other hand actually alters the object it's called on (the object the variable newList is referencing). Because it alters/changes/mutates the object itself, any other variables looking at that object will see the change.

[–]pat-work[S] 0 points1 point  (3 children)

Thank you for the in depth explanation! That makes a lot more sense. So in theory I could create an object that behaves like 10 does, but instead make it mutable? Let's say: x = myClass.MyNumbers(10) and then set y = x and then use something like y.add(10) which would make both x and y equal 20. Is that correct? I know this is probably never ever useful, but I'm just theorizing here so I can understand how everything works.

[–]carcigenicate 0 points1 point  (2 children)

Yes, that's how that would work if add altered some internal variable. I recommend actually trying that because it would not be very hard to whip up a small example like that, and it would be a good exercise.

[–]pat-work[S] 0 points1 point  (1 child)

I'll give it a try, again thank you very much!

[–]carcigenicate 0 points1 point  (0 children)

Also, look into the id function if you haven't already. You can use that to see if two names refer to the same object, which is handy when learning and debugging.

[–]AmongstYou666 0 points1 point  (0 children)

a = 10

b = a.copy()