Main Content

Mutable v Immuatble objects in Python, and the implication

Archive - Originally posted on "The Horse's Mouth" - 2015-02-24 09:38:46 - Graham Ellis

In python, "everything is an object" - well, at least everything you name, and lots of standard system things too, are!

Some object types are immutable. That means tha once they have been created, they cannot be modified and any code that looks like it modifies them in reallity produces a new object that's an amdened copy with the new data.

Other object types are mutable. And in that case, they can be amended in situ once they have been created.

One of the effects of "mutable v immutable" is that is you pass an immutable object into a function or method and (attempt to) change it there, you will NOT change it in the main code. But if you pass a mutable object into a function or method, you WILL change it in the main code. See [example source].

  def one (first):
    first += 5
    return first
  f = 27
  x = one(f)
  print f


result - the ORIGINAL 27

  def two (second):
    second += [5]
    return second
  s = [27]
  y = two(s)
  print s


result - a MODIFIED list [27,5]

• Immutable obects provided by Python ... int, float, str, tuple
• Muttable objects ... most others!