vinita
vinita

Reputation: 597

python objects : digging deeper

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

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

  1. Small integers are cached in CPython, that's why their id's are same.
  2. Integers are immutable, so modifying(i.e assigning it to a new object) one will not affect the other references.
  3. Lists are mutable, so modifying any reference(in-place modification) to a mutable object will affect other references as well.
  4. Small strings can have same id's too:

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

Yuushi
Yuushi

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

Related Questions