Variable Assignment

Changes to a variable result in new objects

     a = a + 1
  • This creates a new object with value a+1.
  • The name "a" is set to refer to the new object (reference count of old object decremented).
  • The value of the old object is not changed!
  • Note: This is different than how it works in a language like C.
  • Variables do not represent fixed memory locations.
  • This is one reason why there are no ++,--,+= operators.

Strange behavior of reference counting

     a = [3,4,5,6]
     b = a
     a[2] = -10
     print b
  • What is the output?
     [ 3, 4, -10, 6]
  • Why? "b" refers to the exact same object as "a".
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 46
July 17, 2000, beazley@cs.uchicago.edu
>>>