What Is Immutable Data Type in Python Give Example?

//

Larry Thompson

What Is Immutable Data Type in Python? Give Example.

Python is known for its flexibility and extensive range of data types. One important concept to understand is the distinction between mutable and immutable data types. While mutable data types can be modified, immutable data types cannot be changed once they are created.

Immutable Data Types in Python

Here are some examples of immutable data types in Python:

  • Numeric Types: Integers, floats, and complex numbers are all immutable in Python. Once you assign a value to these variables, you cannot change them.
  • Strings: Strings are sequences of characters and are also immutable.

    Any attempt to modify a string will result in the creation of a new string object.

  • Tuples: Tuples are ordered collections of elements that can be of different data types. Once a tuple is created, its elements cannot be changed. However, you can create a new tuple by concatenating or slicing existing tuples.

Example:

To illustrate the concept of an immutable data type, let’s consider an example using strings.

# Create a string
my_string = "Hello, world!"

# Attempt to modify the string
my_string[0] = 'J'

In this example, we first create a string variable called my_string. However, when we try to change the first character of the string from ‘H’ to ‘J’, an error will occur:

TypeError: 'str' object does not support item assignment

This error message indicates that strings are immutable in Python, and we cannot modify individual characters. Instead, we need to create a new string if we want to make any changes.

Understanding immutable data types is crucial for writing efficient and bug-free code. By using immutable data types, you can avoid unexpected changes and ensure the integrity of your data.

Conclusion

In this tutorial, we discussed the concept of immutable data types in Python. Immutable data types, such as numeric types, strings, and tuples, cannot be modified once they are created.

We also demonstrated an example using a string to illustrate how attempting to modify an immutable object results in an error. Remembering the difference between mutable and immutable data types is essential for writing reliable Python code.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy