Sub topic 1
Strings Are Immutable: Methods Return New Values
Prerequisites
This chapter assumes you can run Python code in a script or the REPL (the interactive prompt). You should know how to create strings, lists and tuples, call methods and read their return values, and write a basic for loop. You do not need to know anything about split or join yet. This chapter prepares the ground for both.
Why this chapter comes first
Nearly every string method in Python, including split, join, partition and splitlines, shares one rule: it never changes the string you call it on. It gives you a new value. If you forget this, you get bugs where a method runs without an error and the data stays the same.
By the end of this chapter you will be able to:
- Explain what "immutable" means for a Python string.
- Predict what happens when you call a string method and ignore its result.
- Tell the difference between a name, an object, and the value a method returns.
- Recognise the shape of results from
splitandjoin, which the later chapters build on.
What immutable means
A Python str is an immutable sequence of characters. A sequence is an ordered collection you can index and loop over. Immutable means that once the string object exists, its contents cannot change.
You can read characters by index:
word = "hello"
print(word[0]) # h
print(word[-1]) # o
print(word[1:4]) # ell
print(len(word)) # 5You cannot assign to a position:
word = "hello"
try:
word[0] = "J"
except TypeError as error:
print(error) # 'str' object does not support item assignmentPython raises TypeError because the string object has no way to change one of its characters. Compare this with a list, which is mutable (changeable in place):
letters = ["h", "e", "l", "l", "o"]
letters[0] = "J"
print(letters) # ['J', 'e', 'l', 'l', 'o']The list object changed. The string object cannot.
Methods return new values
Because a string cannot change, any method that appears to "modify" a string must build a different string and return it. The original stays as it was.
name = " Ada Lovelace "
cleaned = name.strip()
print(repr(name)) # ' Ada Lovelace '
print(repr(cleaned)) # 'Ada Lovelace'repr shows the string with its quotes, so the spaces are visible. After the call, name still holds the original text. cleaned holds a second, separate string.
The most common bug: ignoring the return value
title = "python"
title.upper() # result is created, then thrown away
print(title) # pythonThe call title.upper() works correctly. It creates "PYTHON". But nothing stores that result, so Python discards it. The fix is to use the return value:
title = "python"
title = title.upper() # rebind the name to the new string
print(title) # PYTHONThis applies to the methods in this tutorial in the same way:
text = "a,b,c"
text.split(",") # returns a list, which is discarded
print(text) # a,b,c
parts = text.split(",") # keep the result
print(parts) # ['a', 'b', 'c']
print(text) # a,b,c (unchanged)Note that split does more than return a new string. It returns a different type, a list. Immutability only says the original is untouched. It does not say the result has the same type.
Names and objects
A variable name in Python is a label attached to an object. Assignment moves the label. It does not edit the object.
a = "cat"
b = a
a = a + "s"
print(a) # cats
print(b) # catStep by step:
a = "cat"creates a string object and attaches the namea.b = aattaches a second name,b, to the same object.a + "s"builds a new string"cats". The nameais moved to it.bstill points at the original"cat".
If strings were mutable, step 3 could have changed what b sees. Immutability prevents that, which is why strings are safe to share between names, pass to functions and use as dictionary keys.
Identity: seeing the new object
The built-in id function returns a number that identifies an object while it exists. You can use it to confirm that a method produced a new object.
s = "hello"
before = id(s)
s = s + "!"
after = id(s)
print(before == after) # False
print(s) # hello!Treat this as a way to observe the behavior, not as something to rely on in programs. Python may reuse objects in some cases, for example when a method has nothing to change. Both of these are allowed:
s = "hello"
print(s.strip() is s) # True in CPython, because nothing needed stripping
print(s.upper() is s) # FalseThe first result is an implementation detail of CPython (the standard Python interpreter). Do not write code that depends on whether two equal strings are the same object. Use == to compare text. Reserve is for checks such as x is None.
Methods you will meet in this tutorial
All of these follow the rule. None of them alter the original string.
| Method | Returns | Original changed? |
|---|---|---|
| `s.split(sep)` | a list of strings | No |
| `s.rsplit(sep, n)` | a list of strings | No |
| `s.splitlines()` | a list of strings | No |
| `s.partition(sep)` | a tuple of three strings | No |
| `sep.join(items)` | a new string | No |
| `s.strip()`, `s.upper()`, `s.replace(a, b)` | a new string | No |
The table shows the result types. They matter because later chapters rely on them. A list is mutable, a tuple is not, and a string never is.
What you can mutate: the results
The immutability rule applies to the original string. The list that split returns is a normal list, and you can change it freely.
line = "red green blue"
colors = line.split()
colors[0] = "crimson"
colors.append("yellow")
print(colors) # ['crimson', 'green', 'blue', 'yellow']
print(line) # red green blueEditing colors has no effect on line. The pieces in the list are new string objects, and the list holds references to them. This is a useful pattern when you need to change text piece by piece:
- Split the string into a list.
- Change the list.
- Join the list back into a new string.
line = "red green blue"
colors = line.split()
colors[0] = "crimson"
new_line = " ".join(colors)
print(new_line) # crimson green blue
print(line) # red green blueThe chapters on split and join develop this pattern in detail. For now, notice that the original line survives, and new_line is a separate string.
Changing one character
Since you cannot assign to an index, changing one character means building a new string. Slicing and concatenation do this:
word = "hello"
changed = "J" + word[1:]
print(changed) # JelloFor several edits, a list of characters can be easier:
word = "hello"
chars = list(word)
chars[0] = "J"
chars[-1] = "y"
print("".join(chars)) # JellyThis is a small preview of join. list(word) makes a list of one-character strings, you edit the list, and "".join(chars) assembles a new string. Another option for simple substitutions is replace:
print("hello".replace("h", "J")) # Jelloreplace also returns a new string. It replaces every occurrence unless you pass a count.
Chaining methods
Since each method returns a new string, you can call another method on the result directly. This is called method chaining.
raw = " Hello, World "
result = raw.strip().lower().replace(",", "")
print(result) # hello worldEach step produces a temporary string that the next step consumes. This works because every call returns a str. It would fail if a method returned None, which is what mutating list methods like sort and append do:
numbers = [3, 1, 2]
result = numbers.sort()
print(result) # None
print(numbers) # [1, 2, 3]This contrast is a common source of confusion:
- String methods return a new value and leave the original alone.
- Many list methods change the list in place and return
None.
Common errors
The mistakes below come directly from forgetting that strings are immutable.
- Discarding the result. Writing
s.strip()on its own line does nothing useful. Assign the result. - Assigning to an index.
s[0] = "x"raisesTypeError. Build a new string with slicing, or edit a list of characters. - Expecting in-place change through another name. Rebinding one name never changes what another name sees.
- Reusing a name for a different type.
data = data.split()is legal, but it makes later code harder to read and can causeAttributeError. - Relying on
isfor text comparison. Use==.
s = "hello"
# Error 1: result ignored
s.upper()
print(s) # hello
# Error 2: item assignment
try:
s[0] = "H"
except TypeError:
print("cannot assign to a string index")
# Fixed versions
s = s.upper()
print(s) # HELLOA note on cost
Because every "change" builds a new string, the cost depends on how many new strings you build and how long they are. One strip() call on a short line is trivial. Building a long string by adding to it thousands of times in a loop creates thousands of intermediate strings, each one a copy of the text so far. A later chapter in this tutorial shows why join avoids this. The reason traces back to the rule in this chapter: strings cannot grow in place.
Summary
- A
stris immutable. You cannot change its characters in place. - String methods return new values. If you want the result, store it.
- Assignment moves a name to a new object. It never edits the old object.
splitreturns a list andpartitionreturns a tuple. The result type can differ fromstr, and the original stays unchanged.- The list from
splitis mutable. Edit it, thenjoinit to get a new string.
Exercise
What do the two print calls show, and why? text = " data " text.strip() print(repr(text)) text = text.strip() print(repr(text))
Show answer
The first print shows ' data ' because text.strip() returned a new string that was never stored, and the original string is immutable. The second print shows 'data' because the result of strip() was assigned back to the name text, which now points at the new string.
Exercise
A learner writes the code below and expects 'hello'. What does it print, and how do you fix it? word = "Hello" word.lower() print(word)
Show answer
It prints Hello, because lower() returns a new string that is discarded and word is not changed. Fix it by assigning the result: word = word.lower(), or print(word.lower()) if you only need the value once.
Exercise
Using only slicing, concatenation and the string "cart", produce "card" without assigning to an index. Then explain why cart[3] = "d" fails.
Show answer
Use "cart"[:3] + "d", which gives 'card'. The assignment cart[3] = "d" fails with TypeError because str objects do not support item assignment: their contents cannot be modified after creation.