immutable
In Python, an immutable object is an object whose value can’t be modified after it’s created. This means that once an immutable object is instantiated, its value can’t change. When you attempt to modify an immutable object, Python will instead create a new object with the updated value, rather than altering the original object.
Numbers (int
, float
), strings, and tuples are common examples of immutable objects in Python. These types ensure that their values remain constant throughout the program execution, which can help with data integrity and consistency.
Understanding immutability is crucial because it affects how you handle data and how Python manages memory. For example, when you pass an immutable object to a function, you can be confident that the function won’t alter the original object, but rather will work with a copy or a reference to the original value.
This behavior contrasts with mutable objects like lists or dictionaries, which can be changed in place.
Example
Here’s an example to illustrate the concept of immutability in Python:
>>> greeting = "Hello."
>>> greeting[5] = "!"
Traceback (most recent call last):
...
TypeError: 'str' object does not support item assignment
In this example, greeting
is a string, which is immutable. When you try to change the character at index 5
, you get a TypeError
exception because immutable object can be changed in place.
Related Resources
Tutorial
Python's Mutable vs Immutable Types: What's the Difference?
In this tutorial, you'll learn how Python mutable and immutable data types work internally and how you can take advantage of mutability or immutability to power your code.
For additional information on related topics, take a look at the following resources:
- Lists vs Tuples in Python (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Differences Between Python's Mutable and Immutable Types (Course)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)