Data Model

Mutability

Some objects change in place, while others return new values.

Objects in Python can be mutable or immutable. Mutable objects such as lists and dictionaries can change in place, while immutable objects such as strings and tuples produce new values instead.

Names can share one mutable object, so a change through one name is visible through another. This is powerful, but it is also the source of many beginner surprises.

The boundary matters across Python: append() mutates a list, string methods return new strings, and sorted() returns a new list while list.sort() mutates an existing one.

Mutable objects can change in place. first and second point to the same list, so appending through one name changes the object seen through both names.

Source

first = ["python"]
second = first
second.append("workers")
print(first)
print(second)

Output

['python', 'workers']
['python', 'workers']
Two names share one mutable list — appending through one name changes the object visible through both.
By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard.

Immutable objects do not change in place. String methods such as upper() return a new string, leaving the original string unchanged.

Source

text = "python"
upper_text = text.upper()
print(text)
print(upper_text)

Output

python
PYTHON

Some APIs make the boundary explicit. sorted() returns a new list, while methods such as append() and list.sort() mutate an existing list.

Source

numbers = [3, 1, 2]
ordered = sorted(numbers)
print(ordered)
print(numbers)

Output

[1, 2, 3]
[3, 1, 2]

Notes

See also

Run the complete example

Example code

Expected output

['python', 'workers']
['python', 'workers']
python
PYTHON
[1, 2, 3]
[3, 1, 2]

Execution time appears here after you run the example.