0

I have a doubt regarding id() in python.

>>> x=2
>>> y=2
>>> id(x)
94407182328128
>>> id(y)
94407182328128

But if i do the same to list,i get different id's

>>> a=[1,2,3]
>>> b=[1,2,3]
>>> id(a)
139700617222048
>>> id(b)
139700617135528

WHY is it so? why for int type i get the id's same and why different for lists?

Thanks in Advance.

ymdatta
  • 80
  • 7
  • Because `x` and `y` refer to the same object. `a` and `b` do not point to the same object. If you use Java, for example, if you have `int x = 2; int y = 2`, then `x == y` is true as they have the same address in memory. However, if you have `int[] x = {1,2,3}; int[] y = {1,2,3};` `x == y` will be false as they have different addresses in memory. – Eli Sadoff Nov 05 '16 at 16:14
  • See http://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – pynexj Nov 05 '16 at 16:30

1 Answers1

0

Python doesn’t have variables like C. In C a variable is not just a name, it is a set of bits; a variable exists somewhere in memory. In Python variables are just tags attached to objects.

Example:

Tags exaple image

Regarding list part:

You created a new reference .

More details are illustrated in this brilliant video:

https://www.youtube.com/watch?v=EnLAEE1C7X4

anati
  • 264
  • 2
  • 13