Sub topic 4
Indexing and slicing, and what they cost
This chapter assumes you know zero-based indexing from arrays and basic Big-O notation. It also assumes you have read the earlier chapters on code points and UTF-8. Here you will see how to read parts of a string and what each read costs.
Indexing: reading one position
Indexing returns the item at a position. In Python, s[0] is the first character and s[-1] is the last. A negative index counts from the end, so s[-1] means s[len(s) - 1].
An index outside the string raises IndexError. This differs from slicing, which never raises for out-of-range bounds.
Slicing: reading a range
A slice s[start:stop] returns a new string. It includes start and excludes stop. The length of the result is stop - start, when both bounds are inside the string.
s = "hello"
print(s[1]) # e
print(s[-1]) # o
print(s[1:4]) # ell
print(s[3:99]) # lo (bounds are clamped, no error)
print(s[:2]) # he
print(s[::-1]) # olleh (step of -1 reverses)
try:
s[0] = "J"
except TypeError:
print("strings are immutable")
t = "J" + s[1:]
print(t) # JelloAssigning to s[0] fails because strings are immutable. To "change" a string, you build a new one from slices and other pieces. The next chapter explains why languages make this choice.
What indexing costs
The cost of s[i] depends on how the string is stored. The question is whether the program can jump straight to position i.
- Fixed-width storage. Every character takes the same number of bytes, so the address of item
iisstart + i * width. This is O(1). CPython does this. Internally it stores each string with 1, 2, or 4 bytes per code point, chosen by the largest code point in the string. - Variable-width storage. In UTF-8, one code point takes 1 to 4 bytes. To find the i-th code point you must scan from the start and count, which is O(n).
Languages such as Go and Rust store strings as UTF-8. They avoid the scan by indexing by byte offset, not by character position. A byte offset is O(1), but it can land in the middle of a character.
What slicing costs
A slice builds a new string, so it must copy the selected characters. A slice of length k costs O(k), not O(1). Taking s[1:] of a long string copies almost the whole string.
Some languages avoid the copy. Go returns a slice that points into the original bytes, which is O(1). The cost is that a tiny substring keeps the whole original string alive in memory. Java copies in modern versions, because sharing memory caused the same problem.
A common mistake is slicing inside a loop. This code looks linear but is quadratic:
def count_a(s):
count = 0
while s:
if s[0] == "a":
count += 1
s = s[1:] # copies the rest of the string every time
return count
print(count_a("banana")) # 3Each s[1:] copies up to n characters, so n steps cost O(n²) in total. Iterate by index instead: for ch in s or for i in range(len(s)).
Cost summary
| Operation | Fixed-width (CPython) | UTF-8 by byte offset | UTF-8 by code point |
|---|---|---|---|
| `s[i]` | O(1) | O(1) | O(n) |
| `s[a:b]` with copy | O(b - a) | O(b - a) | O(n + b - a) |
| `len(s)` in code points | O(1) | O(n) | O(n) |
CPython stores the length, so len(s) is O(1). A UTF-8 language must scan the bytes to count code points.
Indexing is not the same as a user-visible character
Even with O(1) indexing, s[i] returns one code point. Some visible characters are several code points, such as "e" followed by a combining accent. Indexing then splits what the reader sees as one letter. A later chapter on grapheme clusters covers this.
Exercise
A Python function repeatedly runs s = s[1:] on a string of length n until it is empty. What is its total cost in Big-O, and how would you remove the cost?
Show answer
Each slice copies the remaining characters, so the copies have sizes n-1, n-2, ... 1. The sum is about n²/2, so the cost is O(n²). Loop with for ch in s or an index variable so that no copies are made. The loop then costs O(n).
Exercise
Why is s[i] O(1) in CPython but O(n) when i counts code points in a UTF-8 string?
Show answer
CPython stores every code point of a string at the same width, so it computes the address of item i directly. In UTF-8, code points take 1 to 4 bytes each, so the program must scan from the start to find where the i-th one begins.