Python Variables and Data Types · Lesson 10 of 149

Python Mutable vs Immutable Types

What you will learn

  • The difference between mutable and immutable values
  • Which built-in types are which
  • Why += works differently for text, numbers and lists
  • What identity is: id() and is
  • When to use == and when to use is

This lesson uses lists, tuples and dictionaries as examples before their own chapters. You only need to know that [1, 2] is a list, (1, 2) is a tuple and {"a": 1} is a dictionary (lesson 2.2).

1. Two kinds of values

Some values can be changed after they are made. Some cannot.

Meaning Types
Immutable cannot be changed in place int, float, bool, str, tuple, None, frozenset
Mutable can be changed in place list, dict, set

"In place" means the same value is altered without making a new one.

s = "abc"
s[0] = "x"
TypeError: 'str' object does not support item assignment

Text is immutable. You cannot change a letter inside it. A list is different:

nums = [1, 2, 3]
nums[0] = 99
print(nums)
[99, 2, 3]

The list was changed in place. And a tuple, the immutable cousin of the list, refuses:

t = (1, 2, 3)
t[0] = 9
TypeError: 'tuple' object does not support item assignment
Quick check: is a `dict` mutable?

Yes. You can add, change and remove its items after it is made.

2. "Changing" an immutable value

You can make a text longer, but Python makes a new string and moves the name to it:

word = "hello"
up = word.upper()
print(word, up)
hello HELLO

upper() left word alone and gave back a new string. Immutable values behave like this everywhere: operations return new values.

Mutable values often change in place and return None:

lst = [3, 1, 2]
r = lst.sort()
print(lst, r)
print(sorted([3, 1, 2]))
[1, 2, 3] None
[1, 2, 3]

lst.sort() rearranged the list itself and returned None (lesson 2.3), while sorted(...) made a new sorted list. A common beginner mistake is writing lst = lst.sort(), which stores None.

3. Identity: id() and is

Every value in memory has an identity, a number that never changes during its life. id(x) gives it, and a is b asks: "are a and b the very same object?"

You do not need the actual numbers (they change from run to run). What matters is whether two identities match.

How += differs

x = "ab"
id_before = id(x)
x += "c"
print(id(x) == id_before, x)
False abc

Text is immutable, so x += "c" made a new string, and x now points to it. The identity changed.

y = [1, 2]
id_before = id(y)
y += [3]
print(id(y) == id_before, y)
True [1, 2, 3]

A list is mutable, so y += [3] changed the same list in place. The identity stayed the same.

n = 10
id_before = id(n)
n += 1
print(id(n) == id_before, n)
False 11

Numbers are immutable too: n now points to a different number.

4. == or is?

These two questions are different:

Operator Asks Question in words
== equal values? do they look the same?
is same object? are they the very same thing?
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
True False True
  • a == b is True: the two lists hold the same items.
  • a is b is False: they are two separate lists.
  • a is c is True: c is just another name for the list a (lesson 2.7).

The rule

  • Compare values with ==. Use it for numbers, text, lists and almost everything.
  • Use is for None, True and False: x is None, x is not None. These are single objects.
  • Do not use is to compare numbers or text. It may seem to work for small values, but whether two equal numbers or strings are the same object depends on the Python version and how the program is run. It is not something to rely on.

5. A mutable value inside an immutable one

A tuple cannot change which objects it holds, but if one of them is mutable, that object can still change:

tt = ([1], 2)
tt[0].append(9)
print(tt)
([1, 9], 2)

The tuple still holds the same list and the same number; the list itself changed. Trying tt[1] = 5 still fails with the same TypeError as before.

Worked example: predict the result

name = "Rina"
scores = [70, 80]
name += "!"
scores += [90]
Step Value Changed in place?
1 name is "Rina" (immutable text)
2 scores is [70, 80] (mutable list)
3 name += "!" makes a new string "Rina!" no
4 scores += [90] changes the same list to [70, 80, 90] yes

Final values: name is "Rina!" and scores is [70, 80, 90]. Another name pointing to the old list would also see 90 (see lesson 2.7).

Common mistakes

  • Writing lst = lst.sort(). sort() returns None; use lst.sort() alone, or lst = sorted(lst).
  • Trying to change a character in a string (s[0] = "x"). Build a new string instead.
  • Using is to compare values. Write ==, and keep is for None.
  • Thinking a tuple is frozen all the way down. A list inside it can still change.

Key takeaways

  • Immutable values (int, float, bool, str, tuple, None) cannot change in place; operations return new values.
  • Mutable values (list, dict, set) can change in place.
  • += makes a new object for immutable values and changes the same object for a list.
  • == compares values; is asks whether two names point to the very same object.
  • Use is only for None (and True or False).

Practice

1. Which of these can be changed in place: "hi", [1, 2], (1, 2), {"a": 1}, 5?

Show answer

The list [1, 2] and the dictionary {"a": 1}. The text, the tuple and the number cannot.

2. What does s = "dog" then s.upper() leave in s? How do you keep the capital version?

Show answer

s stays "dog", because text is immutable and upper() returns a new string. Store it: s = s.upper().

3. What is wrong with numbers = numbers.sort()?

Show answer

sort() changes the list in place and returns None, so numbers becomes None. Use numbers.sort() alone, or numbers = sorted(numbers).

4. With a = [1, 2] and b = [1, 2], what do a == b and a is b give?

Show answer

True and False. They hold equal items, but they are two different list objects.

5. How should you test whether result holds None?

Show answer

result is None (or result is not None for the opposite).

6. box = ([1, 2], "x"). Does box[0].append(3) work? Does box[1] = "y" work?

Show answer

The first works: the tuple holds the same list, and the list changes to [1, 2, 3]. The second fails with a TypeError, because a tuple cannot be reassigned.