Skip to content

Module 17 · Advanced Python Concepts — topic 1 of 14

Mutable versus immutable objects

Which Python types can change in place (lists, dicts, sets, most objects) and which cannot (int, float, str, tuple, frozenset), what 'changing' an immutable value really does, hashability, and how mutability affects function arguments.

Beginner 10 min read·Lesson 247 of 306 in Python Programming

Learning objectives

  • Classify built-in types as mutable or immutable
  • Explain what happens when an immutable value is 'changed'
  • Predict how functions affect the arguments they receive

Definition

A mutable object can be changed after it is created; an immutable object cannot. Operations that seem to modify an immutable value actually create a new object and rebind the name to it.

Introduction

Why does s.upper() leave s unchanged, while lst.append(3) changes lst? The answer is mutability, one of the most important ideas in Python's object model.

Why it matters

Many puzzling bugs — functions that unexpectedly modify data, lists shared between objects, dictionary keys that are rejected — come down to mutability.

Detailed explanation

Immutable types: int, float, bool, complex, str, bytes, tuple, frozenset and None. Mutable types: list, dict, set, bytearray and most user-defined objects.

String and number operations return new objects. a += 1 on an int creates a new int and rebinds a; on a list, += extends the same list in place.

Only hashable (in practice, immutable) objects can be dictionary keys or set members, because their hash must never change. Tuples are hashable if their items are.

A tuple is immutable, but it can contain mutable objects: the tuple's slots can't change, yet a list inside it can.

Function arguments are passed as references to objects. Mutating a mutable argument (append, item assignment) affects the caller's object; rebinding the parameter name does not.

Default parameter values are created once, so a mutable default is shared between calls — use None and create the list inside.

Immutable objects are safe to share and to use as constants; mutable ones should be copied when independence is needed (see Shallow copy and Deep copy).

Syntax

Python
s = "hi"
s.upper() # new string; s unchanged
nums = [1, 2]
nums.append(3) # same list changed in place
frozenset({1, 2}) # immutable, hashable set
  • Immutable: int, str, tuple, frozenset.
  • Mutable: list, dict, set.
  • Only hashable objects can be keys.

Code examples

Changing versus creating

Python
s = "hello"
t = s.upper()
print(s, t)
nums = [1, 2]
nums.append(3)
print(nums)
point = (1, 2)
try:
point[0] = 5
except TypeError as e:
print(e)
Output
hello HELLO
[1, 2, 3]
'tuple' object does not support item assignment

Identity and hashability

Python
a = 10
before = id(a)
a += 1
print(id(a) == before)
lst = [1]
before = id(lst)
lst += [2]
print(id(lst) == before)
print(hash((1, 2)) == hash((1, 2)))
try:
hash([1, 2])
except TypeError as e:
print(e)
Output
False
True
True
unhashable type: 'list'

More examples

Mutability and functions

Python
def shout(words):
words = [w.upper() for w in words] # rebinds the local name only
return words
def shout_in_place(words):
for i, w in enumerate(words):
words[i] = w.upper() # changes the caller's list
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
names = ["asha", "ravi"]
shout(names)
print(names)
shout_in_place(names)
print(names)
print(add_item("pen"), add_item("book"))
print({(1, 2): "tuple keys work"}[(1, 2)])
print({frozenset({1, 2}): "frozenset as key"}[frozenset({2, 1})])
Output
['asha', 'ravi']
['ASHA', 'RAVI']
['pen'] ['book']
tuple keys work
frozenset as key

Step-by-step explanation

  • shout builds a new list and rebinds its parameter, so the caller's list is untouched.
  • shout_in_place assigns into the list it received, so the change is visible to the caller.
  • The None default creates a fresh basket on every call; tuples and frozensets work as dictionary keys because they are immutable.

Expected output

Running “Mutability and functions” prints exactly:

TextOutput
['asha', 'ravi']
['ASHA', 'RAVI']
['pen'] ['book']
tuple keys work
frozenset as key

Practical applications

  • Using tuples as composite dictionary keys such as (city, date).
  • Functions documented as 'modifies the list in place' versus 'returns a new list'.

Best practices

  • Prefer immutable data for constants and keys.
  • Document whether functions modify their arguments.
  • Never use mutable default values.

Common mistakes

Expecting string methods to modify

Avoid

name.strip()
print(name) # still has spaces

Prefer

name = name.strip()

Strings are immutable; methods return new strings.

Mutable default argument

Avoid

def add(item, items=[]):

Prefer

def add(item, items=None):
if items is None:
items = []

The default list is created once and shared by all calls.

Important notes

  • A tuple containing a list is not hashable, because the list inside could change.

Key takeaways

  • Immutable objects never change; operations create new ones.
  • Mutable objects change in place and are shared by references.
  • Only hashable objects can be keys or set members.

Try it yourself

  1. 1
    Write two versions of a function that removes negative numbers: one that modifies the list, one that returns a new list.
  2. 2
    Explain why (1, [2]) cannot be used as a dictionary key.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhy can't ([1], 2) be used as a dictionary key?
Practise this topic