From the course: Python Data Structures: Sets and Frozen Sets
Hashable and iterable - Python Tutorial
From the course: Python Data Structures: Sets and Frozen Sets
Hashable and iterable
- [Instructor] Iterable is an object that is capable of returning its member one at a time. Let us see how. For number in 1, 2, 3. 1,2,3, is a list print number. Now if you print it, we can run the program to see the output. Python three, one, two, three. One after the other, each of the element present inside of the list has got printed. Likewise, strings are also iterable. We can check this out as for letter in Python print letter. Let us run the program to see the output. You can see 1, 2, 3 is the output of our first code snippet and P-Y-T-H-O-N is the output of our second code snippet. One after the other each of the characters of the string Python have got printed. List, set, dictionary, couples, strings. All of these objects are iterable. Hashable is another term that you would encounter in this course often. Here, let us discuss what is exactly meant by hashable. All immutable objects are hashable. Any object that returns a hash value is considered as hashable. Iterable objects like integers, boolean, pupil, strings are all hashable and immutable. While lists, sets, and dictionaries are mutable and unhashable. Strings, as well as frozensets are hashable and immutable. While list sets and dictionaries are mutable and unhashsble. Hash value, for calculating the hash value, we can use a built-in method named as hash, so X is equal to hash. Let us pass integer value 4, print Hash value of integer object 4 is. Now we can print X, Python three. Hash value of integer object 4 is 4. This is the hash value of immutable object. Let us see what is the output when we try finding out the hash value of mutable object. Y is equal to hash, and then we pass a list. Lists are mutable. Print hash value of list object is here. Let us print Y by 10 three. Now you see we got a type error, unhashable type list. As lists are mutable. Lists are unhashable. Mutable objects are unhashable in nature. Now why is the behavior the way it is? And what happens internally inside of hash function is beyond the scope of the current course. So at the moment for understanding of this course, you must just be clear with what is meant by the term hashable. Sets can have only hashable object as its values, and dictionaries also have only hashable objects as it skis.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.