Data Model
Mutability
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']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
PYTHONSome 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
- Lists and dictionaries are mutable; strings and tuples are immutable.
- Aliasing is useful, but copy mutable containers when independent changes are needed.
- Pay attention to whether an operation mutates in place or returns a new value.
See also
- prerequisite: Variables
- next depth: Object Lifecycle
- next depth: Copying Collections
- next depth: Lists
Run the complete example
Expected output
['python', 'workers']
['python', 'workers']
python
PYTHON
[1, 2, 3]
[3, 1, 2]
Execution time appears here after you run the example.