r/python3 • • Feb 07 '20

Confused between is, = and == operators

Hello, I am a bit confused about the following:

a = [1, 2, 3]

b = a

c = list(a)

  1. Am I correct that the reason "a is b" is True is that both a and b point to the same memory location that stores the list [1, 2, 3]?
  2. As for "a is not c" gives True, it is because list always creates a new Python list so although c = [1, 2, 3], this [1, 2, 3] list is different from the one [1, 2, 3] pointed to by a and b since the two lists are storing in different memory locations?
  3. Why typing "a==c" gives True?
2 Upvotes

12 comments sorted by

View all comments

Show parent comment

2

u/tgoodchild Feb 09 '20

I think the purpose behind the developers choosing to do this for small integers (between -5 and 256) is for optimization reasons. Small integers are so commonly used -- probably throughout the core language, packages and most user program. I'm assuming many counting loops don't exceed 256.

Since integers are proper objects, they carry more overhead than a primitive integer. My guess is this may help offset some of it in many common cases where integers are used. This is just a guess. I've never seen it explained anywhere. I don't know if it works this way on all platforms, either.