-2

here is my code

x = 5
y = 5
print(x is y)
print(id(x))
print(id(y))

and the output is

True
1903991482800
1903991482800

I don't know why x and y have the same location here

please help me illustrate this problom! Thanks!

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
PhiLO
  • 1
  • 2
    Does this answer your question? [Two variables in Python have same id, but not lists or tuples](https://stackoverflow.com/questions/38189660/two-variables-in-python-have-same-id-but-not-lists-or-tuples) – B Remmelzwaal Feb 16 '23 at 14:03

1 Answers1

0

your issue is technically a complicated concept, but I will try to explain it to you in simple terms.

Let's say a number, say '3', is stored in your memory. When you declare a = 3, what the Python interpreter actually does is make that variable 'a' point to the memory location where 3 is stored. So if the number 3 is stored in an address like 'xxyyzz', then the moment you declare a = 3, the variable a points to the memory address 'xxyyzz'. Similarly, when you declare another variable b = 3, what happens is variable 'b' also points to the memory location 'xxyyzz'. The 'is' operator in Python compares the memory addresses of those variables, so you get id(a)==id(b) as True.

Hope this helps!