Main.ListMutability History

Hide minor edits - Show changes to markup

February 16, 2010, at 08:44 AM MST by 71.196.160.210 -
Added lines 1-55:

(:source lang=python:)

"""Exploring lists as mutable objects http://openbookproject.net/thinkcs/python/english2e/ch09.html#lists-are-mutable """

a = "banana" b = "banana"

  1. do a and b point to the same object in memory?

id(a) id(b)

  1. Python only created one string, and both a and b refer to it.
  2. lists behave differently. When we create two lists, we get two objects:

a = [1, 2, 3] b = [1, 2, 3]

id(a) id(b)

  1. Since variables refer to objects, if we assign one variable to another,
  2. both variables refer to the same object:

a = [1, 2, 3] b = a id(a) == id(b)

  1. if we change b, that also changes a

b[0] = 5 print a

  1. If we want to modify a list and also keep a copy of the original, we need
  2. to be able to make a copy of the list itself, not just the reference.
  3. This process is sometimes called cloning, to avoid the ambiguity of the word copy.
  4. The easiest way to clone a list is to use the slice operator:

a = [1, 2, 3] b = a[:] print b a == b id(a) == id(b)

  1. the equality operator for lists determines if all elements of the two lists are the same
  2. Now we are free to make changes to b without worrying about a:

b[0] = 5 print a

(:sourceend:)