Last Updated on March 13, 2023 by Prepbytes
We work with various types of variables and expressions while working in python.
We have different data types to store the values of each variable and expression. Data types in Python are mainly divided into two parts and they are mutable and immutable data types. Both of them have various objects associated with them and each of them has its own advantage and disadvantage according to them we use them. While moving further in this article we will discuss all about immutable data types in detail with examples and their corresponding explanations.
What are Immutable Data Types in Python?
Immutable data types in python are mainly used to store the values of the variable and expressions that cannot be changed once they are created. Hence we cannot alter them. So any attempt in modifying the immutable data types in python will result in the creation of a new object rather than changing the original object. Immutable data types in python are very useful in cases when we want to make sure the value of an object remains constant like when dealing with constant hash values.
Some of the Immutable Data Types in Python are:
- int
- float
- String
- Tuple
- Frozen Set
Int
We can use the ‘ int’ data to represent integers in python, integers are whole numbers without any fraction part associated with them. They can be positive, negative or zero. This data type is available by default there is no need to install it via any package or module.
The size of an integer in python is not fixed, it only depends on the memory available on the computer. The range is theoretically unlimited but practically it has been imposed by the maximum value of the native integer data type of the computer.
This data type supports all the standard mathematical operations in python like addition, multiplications, subtraction, division, modulo, etc. We can also perform additional operations like bitwise, comparison, and logical operations.
The integer can be represented by ‘int’ or by ‘long’ as long is used to represent higher values.
Example of int data type in python
Here is an example of an integer as an immutable data type in python.
m = 15 print('Before changing, memory address = ', id(m)) m = 22 print('After changing, memory address = ', id(m))
Output
('Before changing, memory address = ', 94813437463368)
('After changing, memory address = ', 94813437463200)
Explanation of the above example
In the above example we can see that when changing the value of the integer that is an immutable data type in python this will create a new object rather than changing the original object as the memory location of both is different.
Float
Like integers they are also one of the immutable data types in python that are used to represent numbers but unlike integers, they are used to represent numbers with a decimal point. They can be positive, or negative or contain functional components.
We can create float in python either by using the float() constructor or simply by including a decimal point in the current numeric value. We can perform basic operations like +, -, /,*.
They have limited precision and cannot represent all the given decimal values exactly which will lead to rounding off the error. We can use the decimal module to get more precise results in the case of decimals.
Example of float data type in python
Now we will look at the example of the float as one of the immutable data types in python
x = 3.14 print(x) print(id(x)) x += 1.0 print(x) print(id(x)) x = x * 2 print(x) print(id(x)) print(type(x))
Output
3.14
94326706553312
4.14
94326706553360
8.28
94326706553288
Explanation of the above example
In the above example we can see that we have created a variable x and every time we are performing an operation on x and changing its value the value is changing but in a different memory as you can see in the output. This will prove that float is one of the immutable data types in python as a new object is created every time we are changing its value.
Strings
They are one of the immutable data types in python and can be considered as the sequence of characters enclosed either within single quotes or double quotes and it cannot be changed once declared.
We can concatenate the strings in python using the + operator and also can be repeated using the * operator and can also be indexed and sliced. Here the index starts from 0 and a negative index means iterating the string from the end.
There are many inbuilt functions present in strings like len() which is used to find the length of the string, replace(), lower(), and upper() which are used to change the case of a string to either lowercase or uppercase.
The strings are Unicode in python and because of that, they contain values from both ASCII characters and non-ASCII characters.
There is a regular expression module in python strings that is used to find or search patterns and manipulate them in various ways.
Example of string data type in python
Now let’s look at the example of string as an immutable data type in python.
# initial string initialstring = 'Welcome to PrepBytes' # Now we will change at index 4 initialstring[4] = 'n' print(initialstring)
Output
Traceback (most recent call last):
File "prog.py", line 4, in
TypeError: 'str' object does not support item assignment
Explanation of the above example
In the above example we have seen that initialstring has been declared and when we were trying to change an element at any index it will give error as the string is an immutable data type in python and its value cannot be changed once initialized.
Tuples
We can refer tuple as the collection of immutable and ordered elements in python. They are similar to lists with basic differences in that they cannot be changed once created, which makes them useful in case the data is changed accidentally. They can be created or declared within parentheses with commas in between.
They are very useful in cases when you want to group the data but don’t want to change the data accidentally. It can store various types of expression together.
They are faster and more memory efficient than lists as they are immutable and do not require much space to manage because they cannot be changed at the same.
Example of tuple data type in python
Below is an example of that proves a tuple is one of the immutable data types in python.
# user will input the tuple inputTuple = ('hello', 'prepBytes', 'python') # now we will print the original tuple print("The actual input tuple by the user is:", inputTuple) # trying to modify the tuple element at index 2 inputTuple[2]= 'C++' # now we will print the input tuple after modification print("Input tuple after modification:", inputTuple)
Output
('The actual input tuple by the user is:', ('hello', 'prepBytes', 'python'))
Traceback (most recent call last):
File "prog.py", line 6, in
TypeError: 'tuple' object does not support item assignment
Explanation of the above example
In the above example we can see that we have created a tuple and when printing the original tuple without changing anything it is showing the correct answer. But when we try to change the value of a tuple and after that printing that tupple will result in an error.
Frozen Sets
It is an unordered and immutable collection of unique elements similar to a set. The main difference between a set and a frozen set is that set is mutable whereas the frozen set is immutable. This means you cannot change the frozen set once created.
We can create Frozen sets by using the frozenset() constructor. We will give an iterable object like tuple or list to it and then fit will return the new frozen set object containing the elements of the iterable data type given.
We can use the frozen set as the dictionary keys so that they can be used as a hash value in search as a key in a dictionary. It will support all the general operations like union, and intersection like normal sets in python.
Example of Frozen set data type in python
Below is the example that supports or proves that frozen set is one of the immutable data types in python.
my_frozen_set = frozenset([1, 2, 3, 4, 5]) try: my_frozen_set.add(6) except AttributeError as e: print(f"Error: {e}")
Output
Error: 'frozenset' object has no attribute 'add'
Explanation of the above example
When we make a frozen set it will act as normal but when we try to modify it. This error will be shown.
Properties of Immutable Data Types in Python
Some of the properties that distinguish immutable data types in python from mutable data types in python are given below:
- Cannot be modified: We cannot modify it once created so they will be very helpful in the case of accidental change of data.
- Hashable: They are hashable as they have fixed hash values because they cannot be changed. Because of this, they are used as keys in dictionaries and sets.
- Efficient: They are memory efficient as they have fixed memory so we do not have to assign additional memory to them.
Applications of Immutable Data Types in Python
Some applications of the immutable data types in python are given below:
- Multithreading: As they cannot be changed so they are safe to use in multiple threads without the fear of data corruption. This makes them ideal to use in multithreading.
- Functional programming: They are a core component of functional programming s they focus on that the memory should not be changed. With the help of this, the bugs and unexpected errors can be reduced.
- Configuration data: They are good for storing the configuration data as they are typically read-only and should not be modified at run time. This prevents accidental changes.
Conclusion
Immutable data types in python are those whose values cannot be changed once initialized. They include int, float, string, frozen set, tuple, etc. There are many benefits of using immutable data types in python like they will increase the efficiency, readability of the code, etc. They can also be used as the key in dictionaries. Not all the data types in python are immutable some of them are mutable like lists, dictionaries, etc. As we can change their value after creation. Both mutable and immutable data types in python have their own advantages and disadvantages.
Frequently Asked Questions
Here are some of the frequently asked questions about immutable data types in python.
1. Can you modify the string in python?
No, you cannot modify the strings in python as they are immutable.
2. What are the drawbacks of using immutable data types in Python?
Although there are not many drawbacks but one of the main drawbacks is that they are not useful in the vase when we have to perform many operations on the object value.
3. Can you use immutable data types as dictionary keys in Python?
Yes, we can use them because their value will not change during execution.
4. Are immutable objects shallow-copied or deep-copied in Python?
They are always shallow copied.