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()andis - When to use
==and when to useis
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 == bisTrue: the two lists hold the same items.a is bisFalse: they are two separate lists.a is cisTrue:cis just another name for the lista(lesson 2.7).
The rule
- Compare values with
==. Use it for numbers, text, lists and almost everything. - Use
isforNone,TrueandFalse:x is None,x is not None. These are single objects. - Do not use
isto 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()returnsNone; uselst.sort()alone, orlst = sorted(lst). - Trying to change a character in a string (
s[0] = "x"). Build a new string instead. - Using
isto compare values. Write==, and keepisforNone. - 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;isasks whether two names point to the very same object.- Use
isonly forNone(andTrueorFalse).
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.