Skip to content

Module 3 · Variables and Data Types — topic 12 of 15

Mutable and immutable objects

Some values can be changed in place (lists, dictionaries, sets) and others can’t (numbers, strings, tuples). Learn the difference, how to tell with id(), and why it affects your programs.

Intermediate 14 min read·Lesson 40 of 306 in Python Programming

Learning objectives

  • Classify common types as mutable or immutable
  • Show the difference using id()
  • Predict how changes through one name affect another

Definition

Some values can be changed in place (lists, dictionaries, sets) and others can’t (numbers, strings, tuples). Learn the difference, how to tell with id(), and why it affects your programs.

Introduction

An object is mutable if its contents can change after it is created, and immutable if they can’t. A list is mutable: you can append to it. A string is immutable: “changing” it actually creates a new string.

Why it matters

When two names refer to the same mutable object, a change through one name is visible through the other. This is useful when intended and a common source of bugs when not. Mutability also decides what can be used as a dictionary key.

Detailed explanation

ImmutableMutable
int, float, complex, boollist
strdict
tupleset
frozenset, bytes, Nonebytearray, most objects you create

id(x) returns a number that identifies the object in memory while it exists. If id stays the same after an operation, the object was changed in place; if it changes, a new object was created.

Operations on immutable values always produce new objects: s = s + "!" makes a new string and rebinds s.

Methods such as list.append() change a mutable object in place and return None.

Aliasing: b = a makes both names refer to one object. With a mutable object, a.append(4) is visible through b. Use a.copy() or list(a) to get an independent copy.

Only immutable (hashable) values can be dictionary keys or set members, because their value must not change while stored.

Syntax

Python
items.append(value) # changes items in place
text = text.upper() # builds a new string
copy = items.copy() # independent list
  • Mutating methods change the existing object.
  • Immutable operations return a new object to rebind.
  • copy() avoids unintended sharing.

Code examples

Lists change in place

Python
nums = [1, 2, 3]
before = id(nums)
nums.append(4)
print(nums, id(nums) == before)
Output
[1, 2, 3, 4] True

Strings never change

Python
word = "cat"
before = id(word)
word = word + "s"
print(word, id(word) == before)
Output
cats False

More examples

Aliasing and copying

Python
team_a = ["Asha", "Ben"]
team_b = team_a # same list
team_c = team_a.copy() # separate list
team_a.append("Chen")
print("a:", team_a)
print("b:", team_b)
print("c:", team_c)
try:
lookup = {["x"]: 1}
except TypeError as err:
print("TypeError:", err)
Output
a: ['Asha', 'Ben', 'Chen']
b: ['Asha', 'Ben', 'Chen']
c: ['Asha', 'Ben']
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Step-by-step explanation

  • team_b = team_a creates a second name for the same list.
  • team_c = team_a.copy() creates a new list with the same items.
  • append changes the shared list, so team_a and team_b both show Chen; team_c doesn’t.
  • A list can’t be a dictionary key because it is mutable, so Python raises TypeError.

Expected output

Running “Aliasing and copying” prints exactly:

TextOutput
a: ['Asha', 'Ben', 'Chen']
b: ['Asha', 'Ben', 'Chen']
c: ['Asha', 'Ben']
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Practical applications

  • Functions that receive a list can modify the caller’s list, so APIs document whether they do.
  • Configuration defaults are copied before modification to avoid changing shared settings.
  • Tuples are used for coordinates and records that must not change accidentally.

Best practices

  • Copy mutable data before changing it if others may still use the original.
  • Use tuples for fixed records.
  • Remember that mutating methods return None.

Common mistakes

Assigning the result of append

Avoid

nums = nums.append(5)

Prefer

nums.append(5)

append changes the list in place and returns None, so the assignment loses the list.

Unintended sharing

Avoid

backup = scores
scores.clear()

Prefer

backup = scores.copy()
scores.clear()

Without copy(), backup refers to the same list and is cleared too.

Key takeaways

  • Mutable objects (list, dict, set) can change in place; immutable ones (int, str, tuple) can’t.
  • id() shows whether an operation kept or replaced the object.
  • Names sharing a mutable object see each other’s changes.

Try it yourself

  1. 1
    Show with id() whether t = t + (4,) changes a tuple in place.
  2. 2
    Create two variables that refer to the same dictionary, change it through one, and print it through the other.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic