[Tutor] how to understand unhashable type: 'list'
Steven D'Aprano
steve at pearwood.info
Thu Nov 17 18:35:18 CET 2011
lina wrote:
> Right now I wanna check which are not hash-able, for strings, set, and
> tuple (which I don't understand).
Mutable objects are those that can be changed in place: lists, sets,
dicts are all mutable, because you can change them:
>>> mylist = [1, 2, 3]
>>> mylist[1] = 200
>>> print mylist
[1, 200, 3
Mutable objects are not hashable.
Immutable objects are those that cannot be changed in place: you have to
create a new object. Tuples, frozensets, strings, ints, floats are all
immutable. They are hashable.
> Seems string is hash-able.
>
> Just another quick Q:
>
>>>> basket
> ['apple', 'pineapple', 'apple', 'pear']
>
>>>> hash(basket[1])
> -8771120720059735049
>>>> hash(basket[2])
> 6709291584508918021
The number doesn't mean anything. It's just a number. It gets used by
dictionaries for fast searching, but that's all.
This might help you understand. Here is a very simple hash function that
takes a string and mixes it up to make a number. It isn't very good, it
is a terrible hash function, but it is simple! The Python one is better,
but this will give you an idea of how they work:
def my_hash(string):
num = 102345 # some random number I just made up
for c in string:
num = (num*17 + ord(c)*9) % 3200
return num
Designing a good hash function is very hard.
>>>> print(id(basket))
> 29215848
>>>> print(id(basket[1]))
> 27389096
The id() of an object is just an identity number. Do you have a passport
or driver's licence? Or a social security number? That is like your ID.
It identifies you. Nobody else can have the same ID at the same time.
In CPython, IDs are large numbers, and they are re-usable. If you delete
an object, another object can get the same ID later on.
In Jython and IronPython, IDs start counting at 1 and increase with
every object created. Used IDs are never reused.
IDs aren't important. In 15 years of using Python, I don't think I have
needed to care about the ID of an object once.
--
Steven
More information about the Tutor
mailing list