Reputation: 597
Hi all I know what this code does:
1.] My first problem
x = 4
y = x
But what about this. Why same addresses even for this case?
x = 4
y = 4
id(x)
12345678
id(y)
12345678
2.] My second problem
x = 42
y = x
x = x + 1
print x # Prints 43
print y # Prints 42
x = [1, 2, 3]
y = x
x[0] = 4
print x # Prints [4, 2, 3]
print y # Prints [4, 2, 3]
But why is it that in the case of list, both x
& y
got mutated together by the command x[0] = 4
.
What is so different with lists, in such a behavior?
What makes them behave like this?
And most importantly what is the benefit of such a behavior?
why cant list, variables, tuples have all the properties of each other?
Upvotes: 3
Views: 196
Reputation: 251186
Integer example:
>>> x = 100
>>> y = x
>>> id(x),id(y)
(165193204, 165193204)
>>> x += 1
>>> id(x), id(y) #`x` now points to a new object, `y` still points to the old object
(165193192, 165193204)
Upvotes: 8
Reputation: 26080
Your first problem can be answered with memory optimization. If you dig a little further, for example:
x = 4
y = 4
# Both (may) have the same id
x += 1
# id of x and y will now be different
The second is reference semantics. Since just about everything in Python is really a reference, setting x = y
is simply saying point y
to the same thing that x
points at. If you actually want a completely separate copy, you'll need to say so:
x = [1, 2, 3, 4]
y = x[:]
x[0] = 5
y
>>> [1, 2, 3, 4]
Upvotes: 2