[Tutor] Questions about stdin, stdout, lists and tuples
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 8 Jan 2001 15:41:11 -0800 (PST)
On Mon, 8 Jan 2001, D-Man wrote:
> | Also,
> | lists are like arrays, because I can reassign their values (they are not
> | immutable), whereas tuples are like const arrays, their values cannot be
> | altered?
> |
> | Have I got that right?
>
> Lists are like arrays, but much better. They can grow, be sorted,
> reversed, and you can't overrun your memory bounds!
>
> As far as semantics (except for index bounds errors) and syntax they
> are basically the same.
One thing that tuples can do that lists can't is act as dictionary
keys. For example, since Python knows that tuples are immutable:
city_distances = {}
city_distances[ ('los angeles', 'san francisco') ] = 384
will work. However,
city_distances[ ['los angeles', 'san francisco'] ] = 384
won't. More technically, Python can calculate hash numbers from tuples,
but not lists:
###
>>> mytuple = (1, 2)
>>> mylist = [1, 2]
>>> hash(mytuple)
219750523
>>> hash(mylist)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: unhashable type
###
and that's why they can't be used as keys.
Hope that makes some sort of sense... *grin*