Making Lists, Sets & Dictionaries Immutable in Python

Harnessing the Power of Immutability in Python

CyCoderX
5 min readMay 28, 2024
Photo by Hitesh Choudhary on Unsplash

In the vast and versatile world of Python programming, one inevitably encounters a variety of data structures. Among these, lists, sets and dictionaries stand out as fundamental building blocks. These structures are mutable by default, which means their contents can be altered after they are created. This mutability provides flexibility and dynamism, allowing us to add, remove, or change elements on the fly.

However, this very characteristic of mutability can sometimes become a double-edged sword. In certain scenarios, we need our data to remain constant, or immutable, to ensure the safety and reliability of our code. For instance, when we use these data structures as dictionary keys or when we need to ensure that a function does not change the values of the arguments passed to it, immutability becomes crucial.

In this article, we will delve into the concept of immutability in Python. We will explore how we can transform these mutable structures into their immutable counterparts, thereby harnessing the power of constancy in our code. Whether you’re a seasoned Pythonista or a novice just starting your coding journey, this exploration of immutability will equip you with a deeper understanding of Python’s data structures and how to use them effectively.

Understanding Lists, Sets and Dictionaries

Lists

Lists are ordered data structures where elements are assigned a specific position (index).

list1 = ['apple', 'orange', 'pear']

# 'apple' is at index 0
# 'orange' is at index 1
# 'pear' is at index 2

We use lists to store multiple elements and perform operations on them collectively.

Sets

Sets are unordered collections that only contain unique elements.

set1 = {'apple', 'orange', 'pear'}

# Sets are unordered, meaning 'apple' doesn't come before 'orange'.

Sets are useful for membership testing because they provide O(1) average time complexity for lookups.

Dictionaries

Dictionaries are collections of key-value pairs.

dict1 = {'apple': 4, 'orange': 5, 'pear': 6}

# This dictionary has 3 key-value pairs:
# key value
# apple 4
# orange 5
# pear 6

x = dict1['apple'] # x is 4
y = dict1['orange'] # y is 5
z = dict1['pear'] # z is 6

We use dictionaries for fast access to values using keys, which is typically O(1) in average case scenarios.

Photo by Ying Ge on Unsplash

Mutable vs Immutable

Mutable data structures can be changed after creation. Lists, sets and dictionaries are mutable, meaning we can add, update, or delete their elements.

Immutable data structures cannot be changed after they are created. Python provides immutable alternatives to lists, sets and dictionaries.

Creating Immutable Lists, Sets and Dictionaries

+=================+===================+
| Mutable Version | Immutable Version |
+=================+===================+
| list | tuple |
+-----------------+-------------------+
| set | frozenset |
+-----------------+-------------------+
| dictionary | MappingProxyType |
+-----------------+-------------------+

Tuples (Immutable Lists)

Tuples are like lists, but they are immutable. Once created, their contents cannot be altered. Tuples are created using parentheses or by simply separating items with commas.

tuple1 = (1, 2, 3, 4, 5)
tuple2 = 4, 5, 6, 7, 8 # Parentheses are optional

Tuples are useful when we need an ordered collection of elements that should not be modified.

Example use case: Tuples can be used as dictionary keys since they are immutable.

Frozensets (Immutable Sets)

Frozensets are immutable sets. Once created, their contents cannot be changed. Use the frozenset function to create one.

fs = frozenset({1, 2, 3, 4})

Frozensets can be used as dictionary keys or elements of other sets because they are immutable.

Mapping Proxies (Immutable Dictionaries)

Mapping proxies provide a read-only view of a dictionary. To create a mapping proxy, use MappingProxyType from the types module.

from types import MappingProxyType

original_dict = {'apple': 1, 'orange': 2}
mapping_proxy = MappingProxyType(original_dict)

A mapping proxy ensures that the dictionary cannot be modified, which is useful when you want to expose data without allowing changes.

Example use case: Preventing modifications to configuration settings or constants in a program.

Photo by Clément Hélardot on Unsplash

Conclusion

In conclusion, the journey through Python’s mutable and immutable data structures is a fascinating exploration of the language’s flexibility and robustness. Understanding and using immutable data structures is not just a theoretical concept, but a practical tool that can significantly enhance the reliability and safety of your code.

Immutable data structures act as a safeguard against accidental modifications, a common pitfall that can lead to unexpected bugs and errors. This is particularly important in complex systems where data integrity is paramount and any unintended alteration can have far-reaching consequences. Whether you’re dealing with lists, sets, or dictionaries, Python provides robust and efficient ways to ensure immutability.

In the end, the choice between mutable and immutable data structures depends on the specific requirements of your project. However, having a solid understanding of both and knowing when and how to use them, is an invaluable skill in your Python programming toolkit. As you continue your coding journey, remember that sometimes, constancy and unchangeability can be just as important as flexibility and change.

Final Words:

Thank you for taking the time to read my article.

This article was first published on medium by CyCoderX.

Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!

Join me as we explore the exciting world of tech, data and beyond!

For similar articles and updates, feel free to explore my Medium profile

If you enjoyed this article, consider following for future updates.

Interested in Python content and tips? Click here to check out my list on Medium.

Interested in more SQL, Databases and Data Engineering content? Click here to find out more!

Happy Coding!

What did you think about this article? If you found it helpful or have any feedback, I’d love to hear from you in the comments below!

--

--

CyCoderX

Data Engineer | Python & SQL Enthusiast | Cloud & DB Specialist | AI Enthusiast | Lifestyle Blogger | Simplifying Big Data and Trends, one article at a time.