Sub topic 13
Operators on strings, lists and tuples
This chapter assumes you can run a script or the REPL and know the core built-in types (str, list, tuple, int, bool). It also assumes you know simple assignment and the arithmetic and comparison operators from earlier chapters. Here you will see how the same symbols behave on sequences, where they surprise people, and which alternatives to prefer.
One symbol, several meanings
Python reuses +, *, in, == and < for sequences. The operator is the same, but the operand types decide what it does. Strings, lists and tuples are all sequences, so they share most of the behavior.
| Operator | Meaning on sequences | Result type |
|---|---|---|
| `a + b` | Concatenation: a new sequence with the items of `a`, then `b` | Same type as the operands |
| `a * n` | Repetition: the items of `a` repeated `n` times | Same type as `a` |
| `x in a` | Membership test | `bool` |
| `a == b` | Equal length and equal items, in order | `bool` |
| `a < b` | Lexicographic (dictionary-style) ordering | `bool` |
| `a += b` | Augmented assignment, in place for lists only | Depends on the type |
Concatenation and repetition
print("ab" * 3)
print([1, 2] + [3])
print((1, 2) + (3,))
print([0] * 3)
print("ab" * 0 == "")
print("ab" * -1 == "")Both operands of + must have the same sequence type. A count of zero or less gives an empty sequence. The count must be an int, and 3 * "ab" works the same as "ab" * 3.
Mixing types raises TypeError. Python does not guess what you meant.
for left, right in [("a", 1), ([1], (2,))]:
try:
left + right
except TypeError as error:
print(error)The messages are can only concatenate str (not "int") to str and can only concatenate list (not "tuple") to list. Convert one side explicitly, for example "a" + str(1) or [1] + list((2,)).
Repetition copies references, not objects
[x] * n does not copy x. It repeats the same reference n times. For immutable items such as numbers this is harmless. For mutable items it creates aliases.
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good)The first print shows [[1, 0, 0], [1, 0, 0]], because both rows are the same list. The second shows [[1, 0, 0], [0, 0, 0]], because the comprehension builds a fresh inner list on each pass. The inner [0] * 3 is safe since the items are integers.
Membership
in asks whether a value occurs in the container. What counts as "occurs" depends on the type.
print(3 in [1, 2, 3])
print((1, 2) in [(1, 2), (3, 4)])
print("py" in "python")
print("" in "python")
print("a" not in "python")- For lists and tuples,
incompares each item with==(after an identity check) and stops at the first match. The cost grows with the length of the sequence. - For strings,
intests for a substring, not a single character. The empty string is a substring of every string, so"" in "python"isTrue. - A string on the left of
inmust be a string:1 in "abc"raisesTypeError.
If you do many membership tests on a large collection, convert it to a set once. Set lookups take roughly constant time.
Comparing sequences
== is true when both sequences have the same type family, the same length and equal items. A list never equals a tuple, even with the same contents.
Ordering operators compare item by item and stop at the first difference. If one sequence is a prefix of the other, the shorter one is smaller.
print([1, 2] == (1, 2))
print([1, 2, 3] < [1, 2, 4])
print((1, 2) < (1, 2, 0))
print("apple" < "banana")
print("Z" < "a")This prints False, True, True, True, True. The last result follows from strings being compared by Unicode code point, where "Z" is 90 and "a" is 97. That order is not alphabetical for every language. For user-facing sorting, use str.casefold or the locale module.
Ordering needs every compared pair to be orderable. Equal items are skipped, so only the first differing pair is compared.
try:
print([1, "a"] < [1, 2])
except TypeError as error:
print(error)The first items are equal, so Python compares "a" with 2 and raises TypeError.
Augmented assignment: lists and tuples differ
a += b first tries the in-place method (__iadd__). Lists have one, and it extends the same object. Tuples and strings do not, so Python falls back to a = a + b, which builds a new object.
a = [1, 2]
b = a
a += [3]
print(b)
a = a + [4]
print(a, b)
t = (1, 2)
u = t
t += (3,)
print(t, u)The output is [1, 2, 3], then [1, 2, 3, 4] [1, 2, 3], then (1, 2, 3) (1, 2). The first += changed the list that b also refers to. The explicit a = a + [4] created a new list, so b kept the old one. The tuple was rebound to a new tuple while u still points to the old one.
Note that list += x accepts any iterable, as in a += "xy", which adds two characters. list + x requires a list.
t = ([1],)
try:
t[0] += [2]
except TypeError as error:
print(error)
print(t)The tuple now prints as ([1, 2],) even though an exception was raised.
Building strings in a loop
Because strings are immutable, each + creates a new string and copies the characters. Building a long string in a loop can therefore do quadratic work in the worst case. Some CPython versions optimize simple cases, but you should not rely on that.
parts = []
for number in range(5):
parts.append(str(number))
line = ",".join(parts)
print(line)Collect the pieces in a list and call str.join once. Use + and * for a few short strings, and use f-strings for formatting.
Common mistakes
- Expecting
[1, 2] * [3]to work. Repetition needs an integer, so this raisesTypeError. - Using
*to make a list of lists, which creates shared rows. - Using
inon a string and expecting an item match."ab" in "cabd"isTruebecause it is a substring test. - Relying on
+=to copy. For lists it modifies the original object. - Comparing a list with a tuple using
==and gettingFalse.
Exercise
What do the following lines print, and why? x = [1, 2], y = x, x += [3], print(y), then x = x + [4], print(y).
Show answer
The first print(y) shows [1, 2, 3]. The += on a list extends the same object in place, and y refers to that object. The second print(y) still shows [1, 2, 3]. The statement x = x + [4] builds a new list and rebinds x, so y keeps pointing to the old one.
Exercise
Write a line that creates a 3 by 4 grid of zeros in which changing one cell does not change any other row.
Show answer
grid = [[0] * 4 for _ in range(3)]. The comprehension runs the inner expression three times, so each row is a separate list. Writing [[0] * 4] * 3 would repeat one row three times.