Python is a versatile programming language known for its simplicity and readability. One prominent feature is immutability, which refers to objects whose state cannot be modified once created. Understanding immutable data types is crucial for writing efficient and bug-free source code. This article explains everything about immutable data types, why they matter, and how to use Python.
What are Immutable Data Types in Python?
Immutable data types in Python are mainly used to store the values of variables and expressions that cannot be changed once they are created. Python developers cannot alter them. Immutable data types help to ensure that data remains consistent and safe from unintended changes, which can be particularly beneficial in multi-threaded or concurrent programming environments.
Some of the Immutable data types in Python are:
int
float
String
Tuple
Frozen Set
Int
In Python, we can define the ‘int’ data type to represent integers. Integers are whole numbers without any fractional part associated with them. They can be positive or negative. In Python, the size of the integer is not fixed. Its size depends on the memory available on the computer.
Example of int data type in Python
The following program demonstrates the immutable data type in Python:
Program
m = 34
print('Memory address = ', id(m))
m = 343
print('Memory address = ', id(m))
Float is also one of the immutable data types in the Python language. It is used to represent numbers like integers. They are used to represent numbers with a decimal point. It can be positive or negative or contain functional components. We create the float in python using the float() constructor or simply by including a decimal point in the current numeric value. We can perform basic operations like +,-,/,*.
Example of float data type in Python
Now, Let’s take the example of the float as one of the immutable data types in Python:
Program
x = 3.14
print(x)
print(id(x))
x += 2.0
print(x)
print(id(x))
x = x * 5
print(x)
print(id(x))
print(type(x))
Strings are immutable data types in the Python language. They are sequences of characters enclosed in either single quotes (‘), double (‘“), or triple quotes (”” or ‘’’’). Strings are immutable, meaning once they are created, they cannot be modified. Let’s look at some key aspects and operations related to strings in Python.
Tuples are a fundamental data structure in Python. They store multiple items in a single variable. A tuple is an ordered, immutable collection of items. Once a tuple is created, its elements cannot be altered, added, or removed. Tuples are defined by enclosing their elements in parentheses ‘()’ and can contain elements of any data type, including other tuples.
The following program demonstrates the Tuples:
Program
student_info = ("John", 21, "Computer Science", 3.7)
print("Student Info Tuple:", student_info)
name = student_info[0]
age = student_info[1]
major = student_info[2]
gpa = student_info[3]
print("Name:", name)
print("Age:", age)
print("Major:", major)
print("GPA:", gpa)
name_and_age = student_info[:2]
print("Name and Age:", name_and_age)
extra_info = ("Senior",)
full_info = student_info + extra_info
print("Full Info Tuple:", full_info)
repeated_info = student_info * 2
print("Repeated Info Tuple:", repeated_info)
gpa_count = student_info.count(3.7)
print("Count of GPA 3.7:", gpa_count)
major_index = student_info.index("Computer Science")
print("Index of Major:", major_index)
Output
Student Info Tuple: ('John', 21, 'Computer Science', 3.7)
Name: John
Age: 21
Major: Computer Science
GPA: 3.7
Name and Age: ('John', 21)
Full Info Tuple: ('John', 21, 'Computer Science', 3.7, 'Senior')
Repeated Info Tuple: ('John', 21, 'Computer Science', 3.7, 'John', 21, 'Computer Science', 3.7)
Count of GPA 3.7: 1
Index of Major: 2
Frozen Sets
It is an unordered and immutable collection of unique elements similar to a set type. It behaves like a set but cannot be changed once created. This immutability makes ‘frozen sets’ hashtable and allows them to be used as dictionary keys or elements of other sets.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Properties of Immutable Data Types in Python
Below are some properties that distinguish immutable data types in Python from mutable data types in Python:
Cannot be Modified: We cannot modify the immutable type, so it is very helpful for storing consistent data in the Python program.
Hashable: The immutable types are hashable, meaning they can be used as keys in the dictionary or elements in sets. This is because their hash value remains constant throughout their lifetime.
Thread-Safe: The immutable object itself cannot be changed; it is, by definition, therefore always thread-safe. Several threads can share the same immutable object, without any risk of data corruption or inconsistency.
Efficient Memory Usage: Python can optimize memory usage for immutable objects. For instance, small integers and short strings are often interned, meaning Python reuses existing objects rather than creating new ones.
Applications of Immutable Data Types in Python
Let’s see some applications of the immutable data types in Python, which are given below:
Multithreading: We cannot be changed so they can safely use the multiple threads without data corruption. This makes it ideal for multithreading.
Functional Programming: It supports the functional programming paradigms by avoiding side effects.
Simplified Debugging: It makes debugging easier by avoiding changes to the object’s state.
Documentation and Clarity: Immutable data type enhances the source code readability and understanding by indicating a fixed rate.
Conclusion
Python immutable data types, like ‘int’, ‘float’, ‘str’, ‘tuple’, and ‘frozen set’, are key to safe source code writing. Once instantiated, these types cannot be changed. They help avoid unexpected bugs and make the source code easier to understand. They are very useful in dictionaries and sets, safe for multi-threaded programs, and ideal for functions that shouldn’t alter their inputs. Using immutable types leads to cleaner, more stable and efficient Python source code.
FAQs
What is the precedence of the ‘lambda’ operator in Python?
The lambda operator has a lower precedence than most other operators. For instance, in the expression ‘lambda s: x+ 2*3, the multiplication (‘2*3’) is evaluated before the addition (‘x+6’).
Why are immutable data types important?
They ensure data integrity by preventing changes, making the source code more predictable and easier to debug.
Can immutable objects be used in mathematical operations?
Yes, immutable objects like ‘int’ , and ‘float’ can be used in mathematical operations. Operations result in new immutable objects reflecting the outcome of the computations.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.