2

In python, I have declared two variables with same value. Strangely, they are pointing to same object. I need to understand how this objects and their corresponding values are assigned.

#!/usr/bin/python

a = 100
b = 100

print id(a)
print id(b)
--------------------
Output :

157375428
157375428
-------------------

I assume, a and b are two different variables with same value. Then why the same object is pointing to both of them ?

idjaw
  • 25,487
  • 7
  • 64
  • 83
Biswajit
  • 415
  • 4
  • 13

3 Answers3

3

Technically a and b are two different variables.

In Python a variable is a just a name. Values are somewhere else and a variable refers to a value.

From the Python documentation

For immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation.

xiº
  • 4,605
  • 3
  • 28
  • 39
3

By calling id(a) you actually get same result as when calling id(100), a and b share the same instance of 100. I know this is quite confusing, almost every other programming language behaves differently. Maybe you shouldn't think a and b as variables but instead "named references" to objects.

NikoNyrh
  • 3,578
  • 2
  • 18
  • 32
  • If id(a) is same as id(100), considering the same logic, "is" operator will be a failure. Consider the piece of code. a = 100 b = 10 print id(a) print id(b) b = 100 print id(a) print id(b) if a is b : print "True" else : print "False" Output : 144481220 144480324 144481220 144481220 True By nature, "is" operator should perform its operation based on the object. But if the variable value is same to anyother variable anytime (as of the variable b in the example), they both are pointing to same object location. By this "is" operator is dependent on the variable value, not to the object – Biswajit Oct 08 '15 at 12:11
  • https://stackoverflow.com/a/2988271/3731823 an interesting point about `is` vs. `==` :) – NikoNyrh Oct 08 '15 at 12:49
0

Python pre-allocates a number of integers (see http://blog.lerner.co.il/why-you-should-almost-never-use-is-in-python/). For instance, on my computer I have:

>>> x = 100
>>> y = 100
>>> x is y
True

But:

>>> x = 10**1000
>>> y = 10**1000
>>> x is y
False

In fact, we can see that only the first 256 positive integers are pre-allocated:

>>> x = 0
>>> y = 0
>>> while True:
...     if not x is y:
...         print x
...         break
...     x += 1
...     y += 1
... 
257
Régis B.
  • 10,092
  • 6
  • 54
  • 90