Home  >  Article  >  Backend Development  >  Is hash() built-in in Python?

Is hash() built-in in Python?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-12 18:06:232278browse

Is hash() built-in in Python?

Is the hash function hash() built-in in Python? Let me introduce you to the relevant knowledge of hash functions:

hash(object)

If object is a hashable object, hash( ) function will return its hash value; if the object does not belong to a hashable object, the hash() function will throw an exception. The hash value is an integer.

Related recommendations: "Python Video Tutorial"

hash('orca_j35') #> 3721949548176702466
hash([1,2]) #> TypeError: unhashable type: 'list

When searching for a dictionary, hash values ​​are used to quickly compare dictionary keys. Objects with the same hash value are treated as the same key by the dictionary.

x = (1,2)y = (1,2)
# x和y是具备不同id的对象
x is y #> False
z = {x:"orca"}
# 只要哈希值相同,便可互换使用
z[y] #> 'orca'

Equal (==) values ​​have the same hash value. Even if two equal values ​​belong to different types, their hash values ​​are the same, such as 1 and 1.0:

1 == 1.0 #> True
hash(1),hash(1.0) #> (1, 1)

tips: Two equal (==) objects must have the same hash value, but returning them does not necessarily hold true.

Note:

For objects with custom __hash__() methods, the hash() function will truncate __hash__ according to the bit width of the host machine. () The return value.

The above is the detailed content of Is hash() built-in in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn