Data Model

Mutability

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

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']
BEFOREfirstsecond["python"]AFTER APPENDfirstsecond["python","workers"]
Two names share one mutable list — appending through one name changes the object visible through both.

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.