Which data types are immutable in Python?


In this article, we will explain the immutable datatypes in Python.

Python considers everything to be an object. A unique id is assigned to it when we instantiate an object. We cannot modify the type of object, but we may change its value. For example, if we set variable a to be a list, we can't change it to a tuple/dictionary, but we may modify the entries in that list.

In Python, there are two kinds of objects. On the one hand, there are objects that can change their internal state (the data/content inside the objects), i.e. they can be changed using predefined functions or methods, and on the other hand, there are objects that cannot change their internal state (the data/content inside the objects).

In Python, there are 2 types of objects:

  • mutable objects

  • immutable objects.

To conclude the difference, mutable objects can change their state or content, but immutable objects cannot.

Immutable datatypes

Immutable datatypes are objects that cannot be modified or altered after they have been created (for example, by adding new elements, removing elements, or replacing elements). Python's immutable data types are:

  • Int

  • Float

  • Tuple

  • Complex

  • String

  • Stringfrozen set [note: immutable version of the set]

  • Bytes

When you make changes to immutable objects, the memory where they were stored during initialization is updated.

Int

In computer programming, integers are whole numbers that can be positive, negative, or 0 (..., -1, 0, 1,...). An integer is also referred to as an int.

As with other programming languages, commas should not be used in numbers of four digits or more, thus put 1,000 as 1000 in your code.

  • int − Signed Integers

  • long − Long integers for representing higher values

Example

Print integers in a simple way as:

print(10) print(-5) # performing math operations with integers sum_int = 20+30 print(sum_int)

Output

On executing, the above program will generate the following output –

10
-5
50

In Python applications, integers can be used in various ways, and as you learn more about the language, you will have numerous opportunities to work with integers and learn more about this data type.

Since the int data type is immutable, we cannot modify or update it.

As previously stated, immutable objects change their memory address when they are updated.

Example

# input number inputNumber = 5 # printing the memory address of the int variable print('Before updating, memory address = ', id(inputNumber)) # here we are updating an int object by assigning a new value to it. # changing the same input number variable by assigning a new value to it inputNumber = 10 # printing the memory address of the int variable after updating using the id() function print('After updating, memory address = ', id(inputNumber))

Output

On executing, the above program will generate the following output –

Before updating, memory address = 140103023683616
After updating, memory address = 140103023683776

Float

The float data type is used to represent values with decimal points.

The float class represents this value. It is a real number represented in floating-point form. A decimal point is used to specify it. To express scientific notation, the character e or E followed by a positive or negative number may be appended.

Similarly, the float datatype also changes its memory address value after updating.

Example

# printing the type of input numbers number_1 = 4.5 print("Type of 4.5:", type(number_1)) number_2 = -0.05 print("Type of -0.05:", type(number_2)) number_3 = 3.04e20 print("number_3: ", number_3) print("Type of 3.04e20:", type(number_3))

Output

On executing, the above program will generate the following output –

Type of 4.5: <class 'float'>
Type of -0.05: <class 'float'>
number_3: 3.04e+20
Type of 3.04e20: <class 'float'>

A trailing decimal point is used to ensure that a variable is a float rather than an integer, even if it is a whole number. Take note of the difference when a decimal point follows a whole number −

Example

# printing the type of input numbers number_1 = 10 print("Type of 10:", type(number_1)) number_2 = 8. print("Type of 8. :", type(number_2))

Output

On executing, the above program will generate the following output –

Type of 10: <class 'int'>
Type of 8. : <class 'float'>

Tuple

Tuples are likewise immutable, which means we can't append or update anything in them. While modifying any item in a tuple, we get errors 'tuple' object does not support item assignment.

Example

# input tuple inputTuple = ('hello', 'tutorialspoint', 'python') # printing the original input tuple print("The original input tuple:", inputTuple) # modifying the tuple element at index 2 using indexing inputTuple[2]= 'welcome' # printing input tuple after modifying print("Input tuple after modification:", inputTuple)

Output

On executing, the above program will generate the following output –

The original input tuple: ('hello', 'tutorialspoint', 'python')
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    inputTuple[2]= 'welcome'
TypeError: 'tuple' object does not support item assignment

We took a tuple with some random values and then changed the element of the list with another random value, because tuples are immutable data types, the value of the element is not changed and an exception is thrown.

Complex

The complex numbers are represented as realpart+imaginarypart<j>.

Example

inputNumber = 1+2j print(type(inputNumber))

Output

<class 'complex'>

String

Because strings are immutable, we cannot append or update anything in them. While modifying any part of the string, we encountered problems indicating that strings are not mutable in nature.

Example

# input string inputString = 'Welcome to tutorialspoint python' # changing the string character at index 1 inputString[1] = 'a' print(inputString)

Output

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    inputString[1] = 'a'
TypeError: 'str' object does not support item assignment

Frozenset

The only difference between Frozenset and Set is that it is immutable. That means you can't change the set after you've created it.

Example

frozen_set = frozenset(("hello", "tutoraialspoint", "python")) # adding new item to frozen_set # we cannot modify it as the frozenset is immutable frozen_set.add("codes")

Output

Traceback (most recent call last):
  File "main.py", line 4, in <module>
frozen_set.add("codes")
AttributeError: 'frozenset' object has no attribute 'add'

Conclusion

In this article, we learned about immutable Python data types. We also demonstrated how immutable they are with an example.

Updated on: 09-Sep-2023

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements