Tuple question
Benjamin Niemann
pink at odahoda.de
Sun Sep 5 08:37:31 EDT 2004
Roy Smith wrote:
> "Donn Cave" <donn at drizzle.com> wrote:
>
>>I expect it's used relatively infrequently, and for different
>>reasons. "if len(info) == 5", for example - just from that
>>line from a relatively popular Python application, would you
>>guess info is a list, or a tuple?
>
>
> I'd guess it was something which had a __len__ method.
>
>
>>Maybe the problem is that tuples have too many features already.
>>It's sort of silly that they're indexed by number, and if that
>>weren't allowed, we would find fewer people trying to make lists
>>of them.
>
>
> If tuples weren't indexed, the only way you'd be able to access the
> elements would be to unpack them, which would be rather inconvenient.
> Unless of course you had an alternate way to name the elements, but if
> you're going to allow named element access, and forbid indexed access,
> then you might as well just create a normal class instance.
>
> The more I look into this, the more I realize just how inconsistent the
> whole thing is.
>
> For example, tuples can be used as dictionary keys because they are
> immutable. Or so it's commonly said. But, that's not true. The real
> reason they can be used as keys is because they're hashable. If you try
> to use a list as a key, it doesn't complain that it's immutable, it
> complains that it's unhashable:
>
>
>>>>d = {}
>>>>d[[1, 2]] = 3
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: list objects are unhashable
>
> Furthermore, regular objects can be used as keys, even though they *are*
> mutable. You can do this:
>
> class data:
> pass
>
> key = data ()
> key.x = 1
> key.y = 2
>
> d = {}
> d[key] = None
>
> dictKey = d.keys()[0]
> print dictKey.x, dictKey.y
>
> key.x = 42
> dictKey = d.keys()[0]
> print dictKey.x, dictKey.y
>
> If a mutable class instance object can be used as a dictionary key, then
> I don't really see any reason a list shouldn't be usable as a key. How
> is a class instance's mutability any less of disqualifier for key-ness
> than a list's mutability?
>
> And, once you allow lists to be keys, then pretty much the whole raison
> d'etre for tuples goes away. And if we didn't have tuples, then we
> wouldn't have to worry about silly syntax warts like t = (1,) to make a
> 1-tuple :-)
A very handy feature of lists is:
a = [1, 2, 3]
b = [1, 2, 3]
if a == b:
print "List equality is based on content"
while:
a = data()
a.x = 42
b = date()
b.x = 42
if a != b:
print "Other objects have an identity that is independent of\
content"
This special behaviour of lists is implemented by implementing the
__eq__ method. Objects with non-standard __eq__ usually don't have the
expected behaviour when used as keys:
a = [1, 2, 3]
b = [1, 2, 4]
d = {}
d[a] = "first"
d[b] = "second"
a[2] = 4
b[2] = 3
print d[[1, 2, 3]]
Which result would you expect here?
More information about the Python-list
mailing list