2
>>> a = 300
>>> b = 300
>>> id(a)
34709776
>>> id(b)
34709824

In above case a and b memory locations are not same

>>> (a, b) = 300, 300
>>> id(a)
34709632
>>> id(b)
34709632

But when assigning using tuple memory locations are same for both a&b. why?

Ravi Kumar
  • 1,769
  • 2
  • 21
  • 31
  • 1
    Because -5 - 256 are the most used numbers. In `(a, b) = 300, 300` you are seeing peephole optimization where the object is reused using multiple assignment. `a, b = 300, 300` would do the same, Interning has a cost so doing it for every number would not be practical – Padraic Cunningham Jul 01 '15 at 17:22
  • thanks @PadraicCunningham i got clarity on Memory allocation, but what about string objects caching? – Ravi Kumar Jul 02 '15 at 05:24
  • http://stackoverflow.com/questions/28329498/why-does-a-space-effect-the-identity-comparison-of-equal-strings/28329522#28329522 – Padraic Cunningham Jul 02 '15 at 09:06

1 Answers1

1

Here's what I got for a a, b = 300, 300:

  2           0 LOAD_CONST               2 ((300, 300))
              3 UNPACK_SEQUENCE          2
              6 STORE_FAST               0 (a)
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

As for a normal a = 300; b = 300 Python uses two separate LOAD_CONST's, my guess would be that it is some sort of optimization for this kind of assignment.

oopcode
  • 1,912
  • 16
  • 26