[Python data structure] hashable, list, tuple, set, Frozenset

Source: Internet
Author: User
Tags hashable python list

Learning cs212 UNIT4 encountered a tuple, list, set the use of the same problem, and the stitching, merging operations. So I was confused. So here's a summary.

Hashable and Unhashable

Hashing is the process of converting some large amount of data to a much smaller amount (typically a single integer) in A repeatable-out-of-the-it can be looked-in-a table in Constant-time ( O(1) ), which was important for high-performance Algorithms and data structures.

Immutability is the idea of an object would not be the change in some important the it have been created, especially in any The might change the hash value of this object.

--from hashable, immutable

There is three concepts to grasp when trying to understand id , and the and the hash == is operators: identity, value and hash value. Not all objects has all three.

  1. All objects has an identity, though even this can is a little slippery in some cases. id The function returns a number corresponding to an object's identity (in CPython, it returns the memory address of the object, but other interpreters may return something else). If the objects (that exist at the same time) has the same identity, they ' re actually both references to the same object. isthe operator compares items by identity, are a is b equivalent to id(a) == id(b) .

    Identity can get a little confusing when you deal with objects that is cached somewhere in their implementation. For instance, the objects for small integers and strings in CPython is not remade each time they ' re used. Instead, existing objects is returned any time they ' re needed. You should not rely on the your code though, because it's an implementation detail of CPython (other interpreters Do it differently or not at all).

  2. All objects also has a  value , though this is a bit more complicated. Some objects do not has a meaningful value other than their identity (so value an identity could be synonymous, in Some CAs ES). Value can defined as what the  = =  operator compares, so any time  a = = b , you CA n say that  a  and  b  have the same value. Container objects (like lists) has a value that is defined by their contents and while some other kinds of objects would have Values based on their attributes. Objects of different types can sometimes has the same values, as with numbers:  0 = = 0.0 = 0J = = Decimal. Decimal ("0") = = fractions. Fraction (0) = = False   (yep,  bool S is numbers in Python, for historic reasons).

    If A class doesn ' t define an  __eq__  method (to implement the  = =   operator), it'll inherit the default version from  Object  and its instances would be compared Solel Y by their identities. This was appropriate when otherwise identical instances could have important semantic differences. For instance, both different sockets connected to the same port of the same host need to being treated differently if one is F Etching an HTML webpage and the other are getting an image linked from that page, so they don ' t has the same value.

  3. In addition to a value, some objects has a  hash value , which means they can be used as Dictionar y keys (and stored in  set s). The function  Hash (a)  returns the object  a ' s hash value, a number based on the OB Ject ' s value. The hash of an object must remain the same for the lifetime of the object, so it is only makes sense for a object to be hash Able if its value is immutable (either because it's based on the object's identity, or because it ' s based on contents of T He object that is themselves immutable).

    Multiple different objects may has the same hash value, though well designed hash functions would avoid this as much as PO Ssible. Storing objects with the same hash in a dictionary are much less efficient than storing objects with distinct hashes Hash collision requires more work). Objects was hashable by default (since their default value was their identity, which is immutable). If you write __eq__ the method in a custom class, Python would disable this default hash implementation, since your __eq__ fun Ction would define a new meaning of value for its instances. You'll need to write a __hash__ method as well and if you want your class to still is hashable. If you inherit from a hashable class but don ' t want to is hashable yourself, you can set in the __hash__ = None class body.

    --from difference between hash () and ID ()

List

Lists is mutable sequences, typically used to store collections of homogeneous (same) items (where the precise deg Ree of similarity would vary by application).

"" "Python list concatenate:>>> [[0, 0]] + [' Fill x '][[0, 0], ' Fill x ']>>> [[0, 0]] + [' Fill X ', (4, 0)] [ [0, 0], ' Fill X ', (4, 0)] "" "

  

Tuple

Tuples is immutable sequences, typically used to store collections of heterogeneous (heterogeneous, different ingredient) data (such as the 2-tuples produced by the Enumerate () built-in). Tuples was also used for cases where an immutable sequence of homogeneous data was needed (such as allowing storage in a SE T or dict instance).

Set, Fronzeset

A Set object is an unordered collection of distinct hashable objects. (This means the set is mutable, but it's member must be immutable, so

# set Memmber must be immutable
>>> A_set.add ([Traceback]) (most recent): File "<stdin>", line 1, in <module> Typeerror:unhashable type: ' List '
# but set are mutable, so it can add member
>>> A_set.add ((4, 9))

>>> A_set

{(0, 0), (4, 9)}

Common uses include membership testing, removing duplicates from a sequence, and computing mathematical, operations such as Intersection, Union, difference, and symmetric difference.

The frozenset type is immutable and hashable -its contents cannot was altered after it was created; It can therefore is used as a dictionary key or as an element of another set.

But I get in trobule when intialize a set.

# problem when initialize a set>>> {(0, 0)} {(0, 0)}# the only return one ' 0 ' >>> set ((0, 0)) {0}

  

  

[Python data structure] hashable, list, tuple, set, Frozenset

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.