lists and tuples

John Hunter jdhunter at ace.bsd.uchicago.edu
Sun Jun 29 15:12:54 EDT 2003


>>>>> "Gerrit" == Gerrit Holl <gerrit at nl.linux.org> writes:

    Gerrit> John Hunter wrote: I don't understand. I really don't
    Gerrit> understand.
    >>  For me, the most important distinction is that because lists
    >> are mutable, they cannot be used as keys in a dictionary.

    Gerrit> This is probably a basic question, but I can't see why
    Gerrit> mutable objects can't be used as dictionairy keys. Why
    Gerrit> would this be impossible:

Consider this example

  x = (1,2,3)
  y = (1,2,3)
  print id(x), id(y)   # x and y are different objects
  m  = {}
  m[x] = 1
  print m.has_key(y)  # yes it does

This is the default behavior and seems reasonable.  Even though x and
y are different objects, they are equal, and hash to the same thing,
and can both be keys in the dictionary.

Now consider the case where mutable objects are allowed to be keys to
dictionaries.  How would you handle this case?

 x = [1,2]
 y = [1,2,3]
 m = {}
 m[x] = 1    # illegal, but this is a hypothetical
 x.append(3)
 print m.has_key(y), m.has_key(x), m.has_key([1,2])

You could make rules to handle this case, but there is an inherent
ambiguity.  Do you allow only the object x to act as a key, which is
more limiting than the current implementation?  Anything that is equal
to x in it's current mutated state?  Anything that equals x in the
state it was in when you added it as a key to the dict?

This may not have anything to do with the reason mutable objects are
not allowed as keys to dicts, but it does point to a potential source
of problems and gotcha's if they were allowed.

John Hunter






More information about the Python-list mailing list