Main Content

Python for loops - applying a temporary second name to the same object

Archive - Originally posted on "The Horse's Mouth" - 2011-09-14 06:45:24 - Graham Ellis

If you write a for loop in Python to go through each element of a list, you assign an extra (temporary) name to each member of the list while within the loop. So than any changes made to the named variable will also be changes to the object in the original list. However, that's overshaddowed / overtaken by the fact that changes to immutable objects result in the creation of new objects which the temporary name, but not the original name, point to. So that changes made to IMMUTABLE objects will NOT be seen as changes to objects in the original list.

Int and float primitives, and tuples, are IMMUTABLE.
Lists and dicts are MUTABLE, as are most other objects.

Here's an example showing how the behaviour of lists and tuples differs in this respect - even though both are zero based ordered collections of objects:

  # for loop changes mutable objects in list
 
  stuff = [3,4,[5,6],7,8]
  for item in stuff:
     item *= 2
  print stuff
 
  # for loop leaves immutable objects in tuple
 
  stuff = [3,4,(5,6),7,8]
  for item in stuff:
     item *= 2
  print stuff


And here is how that runs:

  munchkin:ps grahamellis$ python over
  [3, 4, [5, 6, 5, 6], 7, 8]
  [3, 4, (5, 6), 7, 8]
  munchkin:ps grahamellis$ """