Data Model
Mutability
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.