Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
34 views
Iterable - Ordered - Mutable - and Hashable Python Objects Explained
Uploaded by
dhanyafb
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Iterable_Ordered_Mutable_and Hashable Python Objec... For Later
Download
Save
Save Iterable_Ordered_Mutable_and Hashable Python Objec... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
34 views
Iterable - Ordered - Mutable - and Hashable Python Objects Explained
Uploaded by
dhanyafb
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Iterable_Ordered_Mutable_and Hashable Python Objec... For Later
Carousel Previous
Carousel Next
Save
Save Iterable_Ordered_Mutable_and Hashable Python Objec... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 13
Search
Fullscreen
118/23, 12:31 PM Nerable, Ordered, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science Openinapp 7 Gans) signin @n Q . YoU nave z 1ree Memper-only stories iert this Montn. Sign up for Medium and get an extra one é Elena Kosourova (Follow) Mar 15,2022 - 8 min read Listen Nsv vy OH & Iterable, Ordered, Mutable, and Hashable Python Objects Explained Discussing what each of these terms really means and implies, their main nuances, and some useful workarounds tt hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909682" a3118/23, 12:31 PM Nerable, Ordered, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science From Pixabay Iterable, ordered, mutable, and hashable (and their opposites) are characteristics for describing Python objects or data tvpes. Despite being frequently used, these terms are often confused or misu; ©) 154 = Q_ 3 article, we'll discuss what each of them really means and implies, what data types they are related to, the main nuances of these properties, and some useful workarounds. Iterable An iterable object in Python is an object that can be looped over for extracting its items one by one or applying a certain operation on each item and returning the result. Iterables are mostly composite objects representing a collection of items (lists, tuples, sets, frozensets, dictionaries, ranges, and iterators), but also strings are iterable. For all iterable data types, we can use a for-loop to iterate over an object: for i in (1, 2, 3): print(i) Output: L 2 3 For a Python dictionary, the iteration is performed by default over the dictionary keys: det = {'at: 1, 'b': 2} print('Dictionary:', dct) print('Iterating over the dictionary keys:') for i in det: print(4) Output: Dictionary: {'a': 1, 'b': 2} Iterating over the dictionary keys: a b hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" ans.118/23, 12:31 PM Nerable, Ordered, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science If we want to iterate over the dictionary values, we have to use the values() method on the dictionary: print('Iterating over the dictionary values: for i in dct.values(): print(i) output: Iterating over the dictionary values: 1 2 If instead, we want to iterate over both the dictionary keys and values, we should use the items() method: print('Iterating over the dictionary keys and values: for k, v in det. items(): print(k, v) Output: Iterating over the dictionary keys and values: al b2 Alliterable Python objects have the __iter__ attribute, Hence, the easiest way to check if a Python object is iterable or not is to use the hasattr() method on it checking whether the __iter__ attribute is available: print(hasattr (3.14, ' print(hasattr('pi', ' Output: False True We can get an iterator object from any iterable Python object using the iter) function on Ist = [1, 2, 3] print (type(Ist)) hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" 33118/23, 12:31 PM erable, Or iter_obj = iter(1st) print (type(iter_obj)) 1, Mutable, ane Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science Output:
Quite expected (and a bit tautologic), an iterator object is iterable, so we can iterate over it. However, unlike all the other iterables, an iterator object gets exhausted in the process of iteration losing its elements one by one: Ist = [1, 2, 3] ‘iter_obj = iter(1st) print('The iterator object length before iteration:') print(len(List(iter_obj))) for i in iter_obj: pass print('The iterator object length after iteration:') print (len(list(iter_obj))) Output: The iterator object length before iteration: 3 The iterator object length after iteration: 8 Pay attention that there is no direct way to check the length of an iterator object like the 1en() built-in function for the other iterable data types. Hence, to check the number of items in an iterator, we first have to convert it to another iterable, such asa list or tuple, and only then to apply the ten() function on it: Len (List (iter_obj)) « Ordered vs. Unordered Ordered objects in Python are those iterable objects where a determined order of items is kept unless we intentionally update such objects (inserting new items, removing items, sorting items). Ordered objects are strings, lists, tuples, ranges, and dictionaries (starting from Python 3.74), unordered — sets, frozensets, and dictionaries (in Python versions older than 3.7). Ast = [lat, 'b', tt, ta] s = {'a', yey tdty hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" ans.118/23, 12:31 PM erable, Or print(1st) print(s) 1, Mutable, ane Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science Output: ['at, 'b', "ct, ta] fib's tet) tats td'} Since the order in ordered objects is preserved, we can access and modify the object's items by indexing or slicin; Ist = ['at, "bY, ‘ct, 'd"] # Access the 1st item of the list. print (Ist[o1) # Access the 2nd and 3rd items of the list. print (1st[1:3]) # Modify the 1st item. Ist[o] = 'A' print(1st[0]) Output: a ['b', te") A To extract a specific value from a Python dictionary, we commonly use the corresponding key name rather than the key index in the dictionary: det = {'a': print (det['b']) : 5S} Output: 2 However, if we, for some reason, need to extract the value of the key with a known position in the dictionary (let’s say, we know only the position and not the key itself), or a bunch of values for a slice of keys with a defined range of positions in the dictionary, we still can technically do it: det = {'at: 1, 'b': 2, 'e': 3, 'd': 4, 'e!: 5} hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 5113118/23, 12:31 PM Nerable, Ordered, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science # Access the value of the Ist key in the dictionary. print (List (det.values())[0]) # Access the values of the 2nd to 4th keys in the dictionary. print(list(dct.values())[1:4]) # Access the 2nd to 4th keys in the dictionary. print (List (det. keys())[1:4]) Output: 1 [2, 3, 4] ['b', 'c', 'd"] ‘The above workaround is not very straightforward. However, it helps index a Python dictionary by keys or values. In unordered objects, we can’t access individual items: s={'a', 'b', ‘ct, ‘ah print(s[0]) outpu TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_9980/849534030.py in
is = f{tat, "bt, tet, 'd'} ----> 2 print(s[e]) TypeError: ‘set! object is not subscriptable If we have a composite ordered object containing other composite objects we can dig deeper and access the inner items of that object’s items, in the case they are ordered as well. For example, if a Python list contains another Python list, we can access the items of the inner list: Ust_2 = [[1, 2, 3], (2, 2, 3}, 10] print(tst_2[0] (2]) Output: 3 hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" ans.118/23, 12:31 PM lterable, Orderad, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science However, we can’t access the items of the set in that list since Python sets are unordered: print (lst_2[1] (2]) Output: TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_9980/895995558.py in
> 1 print(1st_2[1][21) TypeError: 'set' object is not subscriptable Mutable vs. Immutable Mutable objects in Python are those objects that can be modified. Mutability doesn't necessarily mean the ability to access individual items of a composite object by indexing or slicing. For example, a Python set is unordered and unindexed and nevertheless, it’s a mutable data type since we can modify it by adding new items or removing items from it. On the other hand, a Python tuple is an immutable data type, but we can easily access its individual items by indexing and slicing (without being able to modify them, though). Also, it’s possible to index and slice a range object extracting from it integers or smaller ranges. In general, mutable data types are lists, dictionaries, sets, and bytearrays, while immutable — all the primitive data types (strings, integers, floats, complex, boolean, bytes), ranges, tuples, and frozensets. Let’s explore one interesting caveat about tuples. Being an immutable data type, a tuple can contain items of a mutable data type, e.g,, lists: tpl = ([1, 2], 'a', 'b') print (tpl) Output: (1, 2], 'a', 'b') hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 713118729, 1291 Pm erable, Orderd, Muable, and Hashable Python Objects Explained | by Elona Kosourova | Towards Data Science The tuple above contains a list as its first item. We can access it but can’t re-assign another value to this item: # Access the Ist item of the tuple. print(tpl[o]) # Try to re-assign a new value to the Ist item of the tuple. tpl[o] = 1 Output: (1, 2] TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_9980/4141878083.py in
3 4 # Trying to modify the first item of the tuple —> 5 tpl[e] = 1 TypeError: 'tuple' object does not support item assignment However, since a Python list is a mutable and ordered data type, we can both access any of its items and modify them: # Access the 1st item of the list. print (tpl[o] [@]) # Modify the Ist item of the list. tpl[o][o] = 10 Output: 1 As different than the initial one: result, one of the items of our tuple has been changed, and the tuple itself looks print (tpl) Output: ([10, 2], 'a', 'b') Hashable vs. Unhashable hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 ans118/23, 12:31 PM Nterable, Orderad, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science A hashable Python object is any object that has a hash value — an integer identificator of that object which never changes during its lifetime. To check if an object is hashable or not and find out its hash value (if it’s hashable), we use the hash() function on this object: print (hash(3.14)) Output: 322818021289917443 If the object is unhashable, a typeérror will be thrown: print(hash([1, 2])) outpu: TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_9980/3864786969.py in
> 1 hash([1, 2]) TypeError: unhashable type: ‘list! Almost all immutable objects are hashable (we'll see soon a particular exception) while not all hashable objects are immutable. In particular, all the primitive data types (strings, integers, floats, complex, boolean, bytes), ranges, frozensets, functions, and classes, both built-in and user-defined, are always hashable, while lists, dictionaries, sets, and bytearrays are unhashable. A curious case is a Python tuple. Since it is an immutable data type, it should be hashable. And indeed, it seems so: print(hash((1, 2, 3))) Output: 529344067295497451, hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 ans118/23, 12:31 PM erable, Or Notice also that if we assign this tuple to a variable and then run the hash() 1, Mutable, ane Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science function on that variable, we'll obtain the same hash value: a_tuple = (1, 2, 3) print (hash(a_tuple)) Output: 529344067295497451 What if a tuple contains mutable items, just like the one we saw in the previous section? tpl = ([1, 2], 'a', 'b') print(hash(tpl)) Output: TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_8088/3629296315.py in
1 tpl = ([2, 2], 'a', 'b') ----> 2 print(hash(tpl)) TypeError: unhashable type: ‘list! We see that Python tuples can be either hashable or unhashable. They are unhashable only if they contain at least one mutable item. Interesting that even unhashable tuples, like the one above, have the __hash__ attribute: # Check if a hashable tuple has the '__hash__' attribute. print(hasattr((1, 2, 3), '_hash__')) # Check if an unhashable tuple has the '__hash__' attribute. print(hasattr(([1, 2], 'a', 'b'), '__hash__')) Output: True True hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" sons118/23, 12:31 PM Nerable, Ordered, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science We mentioned earlier that not all hashable objects are immutable. An example of such a case is user-defined classes that are mutable but hashable. Also, all the instances of a class are hashable and have the same hash value as the class itself: class MyClass: pass x = MyClass print (hash (MyClass) ) print (hash(x)) Output: 170740243488 170740243488 In general, when two Python objects are equal, their hash values are also equal: # Check the equal objects and their hash values. print(True==1) print (hash(True) hash(1)) # Check the unequal objects and their hash values. print('god'=="dog') print (hash(' god')==hash('dog')) Output: True True False False Conclusion To sum up, we explored the frequently-used but often misunderstood Python object and data type characteristics, such as iterable, ordered, mutable, hashable, and their opposites, from many sides and in detail, including some particular cases and exceptions, Thanks for reading! hitpstowardsdatascience. comvterable-ordered-mutable-and-hashable-pythor-objects-explained-1254c909082" wnn3118/23, 12:31 PM Nterable, Orderad, Mutable, and Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science You can find interesting also these articles: 16 Underrated Pandas Series Methods And When To Use Them Hasnans, pct_change, is_ monotonic, repeat, and many others towardsdatascience.com When a Python Gotcha Leads to Wrong Results A.curious hard-to-debug Python glitch with rounding numbers levelup.gitconnected.com c ing Toyplots in Python £ High-quality minimalist interactive visualizations ideal for electronic publishing medium.com Data Science DataAnalysis Python —Iterables_-»—- Programming Sign up for The Variable By Towards Data Science Every Thursday, the Variable delivers the very best of Towards Data Science: from hands-on tutorials and cutting- ‘edge research to original features you don't want to miss. Take a jook, By signing up, you will ereate a Medium account ifyou dont already have one, Review ‘ur Privacy Palicy for more information about our privacy practices hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 1213118/23, 12:31 PM Mutable, ané Hashable Python Objects Explained | by Elena Kosourova | Towards Data Science \ & Getthis newsletter) / ned 7 Ev sod emeea hitps:/towardedatascience. comterable-ordered-mutable-and-hashable-pythor-objects-explaned-1254c9b96421 1313
You might also like
Python Mutable vs
PDF
No ratings yet
Python Mutable vs
15 pages
Objects in Python: Session Overview
PDF
No ratings yet
Objects in Python: Session Overview
2 pages
Predefined Objects in Python
PDF
No ratings yet
Predefined Objects in Python
2 pages
Immutable VS Mutable Objects
PDF
No ratings yet
Immutable VS Mutable Objects
6 pages
MUTABLE AND IMMUTABLE (Autosaved)
PDF
No ratings yet
MUTABLE AND IMMUTABLE (Autosaved)
19 pages
Addition on python
PDF
No ratings yet
Addition on python
6 pages
4. Type Casting
PDF
No ratings yet
4. Type Casting
12 pages
I-year-II-SEM-UNIT-2 Digital Notes
PDF
No ratings yet
I-year-II-SEM-UNIT-2 Digital Notes
77 pages
Presentation2
PDF
No ratings yet
Presentation2
39 pages
Python PPT LESSON 3 Understanding Data
PDF
No ratings yet
Python PPT LESSON 3 Understanding Data
20 pages
Unit III Notes-Python Programming(BCA614)
PDF
No ratings yet
Unit III Notes-Python Programming(BCA614)
23 pages
5_String Processing, Exception Handling _ Dictionaries
PDF
No ratings yet
5_String Processing, Exception Handling _ Dictionaries
19 pages
Data Handling
PDF
No ratings yet
Data Handling
17 pages
Python Notebook
PDF
No ratings yet
Python Notebook
9 pages
Final InOne Lecture 9, 10 and 11 Data Structures
PDF
No ratings yet
Final InOne Lecture 9, 10 and 11 Data Structures
69 pages
List
PDF
No ratings yet
List
32 pages
Data Types in Python
PDF
No ratings yet
Data Types in Python
5 pages
Class 3
PDF
No ratings yet
Class 3
2 pages
List
PDF
No ratings yet
List
34 pages
List Dict Set Tuple
PDF
No ratings yet
List Dict Set Tuple
23 pages
Data Handling - Ch-8
PDF
No ratings yet
Data Handling - Ch-8
55 pages
Dictionaries and Sets
PDF
No ratings yet
Dictionaries and Sets
5 pages
Data Handling Part 2
PDF
No ratings yet
Data Handling Part 2
10 pages
9 - Dictionary and Tuples
PDF
No ratings yet
9 - Dictionary and Tuples
40 pages
Adding Items To A Dict May Change The Order of Existing Keys
PDF
No ratings yet
Adding Items To A Dict May Change The Order of Existing Keys
2 pages
Data Analysis Using Python Day_1 to Day_4
PDF
No ratings yet
Data Analysis Using Python Day_1 to Day_4
30 pages
Python For Data Science AI Development
PDF
No ratings yet
Python For Data Science AI Development
7 pages
Data Type Introduction
PDF
No ratings yet
Data Type Introduction
25 pages
Python Data Types
PDF
No ratings yet
Python Data Types
9 pages
Dictionary in Python-1
PDF
No ratings yet
Dictionary in Python-1
38 pages
Python Unit1 Part 4
PDF
No ratings yet
Python Unit1 Part 4
11 pages
Python For Data Cheetsheet
PDF
No ratings yet
Python For Data Cheetsheet
13 pages
Datamodel in Python
PDF
No ratings yet
Datamodel in Python
37 pages
Chapter 007 Data Handling
PDF
No ratings yet
Chapter 007 Data Handling
100 pages
DS ML Python
PDF
No ratings yet
DS ML Python
4 pages
009 Data Handling
PDF
No ratings yet
009 Data Handling
100 pages
Day 4 - Python Lect 3
PDF
No ratings yet
Day 4 - Python Lect 3
28 pages
What are the differences between mutable and immut
PDF
No ratings yet
What are the differences between mutable and immut
2 pages
Data Types in Python
PDF
No ratings yet
Data Types in Python
49 pages
What Are Mutable and Immutable Types?: Objects of Built-In Type That Are Immutable Are
PDF
No ratings yet
What Are Mutable and Immutable Types?: Objects of Built-In Type That Are Immutable Are
18 pages
1 Data fundamentals in Python
PDF
No ratings yet
1 Data fundamentals in Python
39 pages
BDS306B_Module1
PDF
No ratings yet
BDS306B_Module1
11 pages
Python Data Types
PDF
No ratings yet
Python Data Types
3 pages
IPP-M3-C1-Dictionaries_5459_BPLC15B_11-01-2025
PDF
No ratings yet
IPP-M3-C1-Dictionaries_5459_BPLC15B_11-01-2025
22 pages
MTE204 Data Python
PDF
No ratings yet
MTE204 Data Python
45 pages
XI-IP-Module-DATA HANDLING-2021-22
PDF
No ratings yet
XI-IP-Module-DATA HANDLING-2021-22
40 pages
30404234-0eaf-44e6-9f08-c5713bb2567c
PDF
No ratings yet
30404234-0eaf-44e6-9f08-c5713bb2567c
16 pages
Lecture 3 Operators Expression and Data Types
PDF
No ratings yet
Lecture 3 Operators Expression and Data Types
44 pages
Python-Cheat-Sheet
PDF
No ratings yet
Python-Cheat-Sheet
10 pages
Python For Machine Learning
PDF
No ratings yet
Python For Machine Learning
95 pages
8 Python Dictionary Things I Regret Not Knowing Earlier
PDF
No ratings yet
8 Python Dictionary Things I Regret Not Knowing Earlier
8 pages
2.Data Handling
PDF
No ratings yet
2.Data Handling
100 pages
L4_Data Handling
PDF
No ratings yet
L4_Data Handling
75 pages
Introduction To Programming Using Python
PDF
No ratings yet
Introduction To Programming Using Python
11 pages
Mutable Vs Immutable Objects in Python
PDF
No ratings yet
Mutable Vs Immutable Objects in Python
9 pages
2024-12-06-0.45911287650145693
PDF
No ratings yet
2024-12-06-0.45911287650145693
32 pages
Python Introduction
PDF
No ratings yet
Python Introduction
30 pages
Chap 8 Tuples Dictionary
PDF
No ratings yet
Chap 8 Tuples Dictionary
82 pages
Data Handling Part 1 Ip
PDF
No ratings yet
Data Handling Part 1 Ip
30 pages