0

In Python I created integer and list objects as follows:

a = 10
b = 10
x = []
y = []

Then I get the following results while comparing the id of a and b, and the id of x and y

id(a)==id(b)  returns True
id(x)==id(y) returns False

Somewhere I read that assignment in Python never copies data. My question is why x and y do not have the same id?

rabbit
  • 21
  • 4

3 Answers3

1

You must know that python integers ar cached and inmutable, that means that both a and b are labeling the same 10. Lists are objects and they are allocated separetly, thats why their ids are diferent from the beggining

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • What do you mean by Lists are objects?, aren't integers objects in Python? – rabbit Nov 22 '16 at 08:40
  • @Zerihun Everything is object in Python, but integers, floats, and also strings, are immutable. They have methods, but these methods do not modify the object, which is (although full legit) a bit confusing. – Right leg Nov 22 '16 at 08:59
1

Lists are mutable, if the same object was used, when you add an item to one of the list, you'd see the change on the other one as well.

Identity of integers is implementation dependent, and it is usually valid only for small numbers; good reading here.

By the way, == is the equality operator. A shortest (and cleaner) way for id(a)==id(b) is to use the identity operator is. In your case: a is b.

Community
  • 1
  • 1
Pintun
  • 716
  • 1
  • 7
  • 23
0

x = [] is a shorthand for instantiating a new list, which means a new object with a new object ID. Even though x and y are assigned as empty lists, they are simply references to memory locations allocated for the respective lists. If id(x) == id(y) then x and y would share the same object ID, which would effectively mean they share a memory location, or are references to the same object (so any changes made to one would apply to the other).

On the other hand, id(a) == id(b) because they are both integers, which are primitive data types.

Sy Dy
  • 116
  • 5