0

# Hash in python

Hello dear learners, Could you please explain how hash method work in python for dictionaries and sets? What is the formula behind it? And how it reduces the overall speed of the code? Thank you!

6 Answers

+ 3

Public source code of the hash function in cpython:
https://github.com/python/cpython/blob/main/Python/pyhash.c
Basically hash is a function that generates a unique identifier which depends on the data itself. You can consider it as the fingerprint of the object. When you lookup keys in a dictionary or elements of a set, it is very quick because only the hashes are compared, not the entire object.

+ 3

Hash is calculated for each value separately when it is inserted (appended).

+ 2

Tibor Santa, Thank you for your response!
Could you please explain why it is faster? Logically it requires extra time for computing hashes too.

+ 1

I suggest you read about hash tables.
https://en.m.wikipedia.org/wiki/Hash_table
You could imagine them as a library catalog, which contains the reference to all the books in the library and makes it really quick to find, on which shelf to find your book.
Hash tables have practically O(1) time complexity for lookup, which means that the speed does not depend on the size of the collection. Even for a large dictionary or set, the lookup by key is instant, Python does not need to browse through all the elements. That is why it's very fast.

+ 1

Tibor Santa, Thank you! Now it is more clear.
Could you please also explain at what time is the hash value for a dictionary or set calculated? I mean is it already precalculated for all values in python or is it calculated in the time of data set execution?

+ 1

Tibor Santa Thanks! You helped me a lot. Really appreciate it :)

Hot today

What's wrong? :(

1 Votes

Why won't my image display

0 Votes

I have made a calculator in which my % (Percentage) not work correctly for 100%50 or 100%20.

2 Votes

How the answer is 50?

0 Votes

Number of Ones ( C++ ) question!

1 Votes