mutable

In Python, a mutable object allows you to modify its value in place without creating a new object. This characteristic is particularly useful when you need to make frequent changes to data, as it can improve performance by avoiding the overhead of creating new objects. Common mutable data types in Python include lists, dictionaries, and sets.

When working with mutable objects, it’s important to be aware of the implications for your program. For example, if you pass a mutable object to a function, any changes made to the object within the function will affect the original object outside the function. This behavior can be advantageous and requires careful management to avoid unintended side effects.

In contrast, an immutable is an object whose state cannot be modified after it is created.

Example

Here’s a quick example demonstrating the mutability of a list in Python:

Python
>>> numbers = [1, 3, 3]
>>> numbers[1] = 2
>>> numbers
[1, 2, 3]

>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4]

In this example, you use an assignment to change the second value in the list. Then, you use the .append() method to modify the list by adding a new value, demonstrating the mutability of Python lists.

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.

intermediate data-structures python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 9, 2025 • Reviewed by Dan Bader