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))
Output
Memory address = 140712281636312
Memory address = 2316635385616
Float
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))
Output
3.14
3083231773456
5.140000000000001
3083228258480
25.700000000000003
3083228256560
<class 'float'>Strings
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.
The following program demonstrates the Strings in Python:
Program
def main():
single_quoted = 'Hello, World!'
double_quoted = "Hello, World!"
triple_quoted = """Hello,
World!"""
print("1. Creating Strings:")
print("Single quoted:", single_quoted)
print("Double quoted:", double_quoted)
print("Triple quoted:", triple_quoted)
print()
str1 = "Hello"
str2 = "World"
combined = str1 + " " + str2
print("2. Concatenation:")
print("Combined string:", combined)
print()
repeated = "Hello" * 3
print("3. Repetition:")
print("Repeated string:", repeated)
print()
text = "Python"
first_char = text[0]
last_char = text[-1]
print("4. Indexing:")
print("First character:", first_char)
print("Last character:", last_char)
print()
substring = text[1:4]
print("5. Slicing:")
print("Substring (1:4):", substring)
print()
length = len(text)
print("6. Length:")
print("Length of text:", length)
print()
text = "Hello, World!"
upper_text = text.upper()
lower_text = text.lower()
title_text = text.title()
stripped_text = text.strip()
replaced_text = text.replace("World", "Python")
words = text.split(", ")
joined_text = " ".join(words)
find_index = text.find("World")
print("7. String Methods:")
print("Upper case:", upper_text)
print("Lower case:", lower_text)
print("Title case:", title_text)
print("Stripped text:", stripped_text)
print("Replaced text:", replaced_text)
print("Words split:", words)
print("Joined text:", joined_text)
print("Index of 'World':", find_index)
print()
if __name__ == "__main__" :
main()
Output
- Creating Strings:
Single quoted: Hello, World!
Double quoted: Hello, World!
Triple quoted: Hello,
World!
- Concatenation:
Combined string: Hello World
- Repetition:
Repeated string: HelloHelloHello
- Indexing:
First character: P
Last character: n
- Slicing:
Substring (1:4): yth
- Length:
Length of text: 6
- String Methods:
Upper case: HELLO, WORLD!
Lowercase: hello, world!
Title case: Hello, World!
Stripped text: Hello, World!
Replaced text: Hello, Python!
Words split: [‘Hello’, ‘World!’]
Joined text: Hello World!
Index of ‘World’: 7
Tuples
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: 2Frozen 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.

POSTGRADUATE PROGRAM IN
Multi Cloud Architecture & DevOps
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.
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.
What is the precedence of the ‘lambda’ operator in Python?
Why are immutable data types important?
Can immutable objects be used in mathematical operations?
Updated on September 3, 2024
