Sub topic 13
Operators on strings, lists and tuples
This chapter assumes you know the core types str, list and tuple, and how to run code in a script or the REPL. Sequences are ordered collections. Python reuses familiar operators on them, and the meaning changes with the type.
Concatenation and repetition
+ joins two sequences of the same type into a new one. * with an integer repeats a sequence.
print("ab" + "cd")
print("ab" * 3)
print([1, 2] + [3])
print((1, 2) * 2)
print([0] * 4)This prints abcd, ababab, [1, 2, 3], (1, 2, 1, 2) and [0, 0, 0, 0]. Neither operand is changed. Python builds a new object each time.
Both sides of + must be the same type. "a" + 1 and [1] + (2,) both raise TypeError. Convert first, for example "a" + str(1) or [1] + list((2,)).
Repetition copies references
* repeats references to the same elements. That is harmless for numbers and strings, which cannot be changed. It causes a bug with nested lists.
grid = [[0] * 3] * 2
grid[0][0] = 9
print(grid)
safe = [[0] * 3 for _ in range(2)]
safe[0][0] = 9
print(safe)The first print shows [[9, 0, 0], [9, 0, 0]], because both rows are the same list. The second shows [[9, 0, 0], [0, 0, 0]]. Use a comprehension when each element must be its own object.
Comparing sequences
Sequences of the same kind compare element by element, starting from the left. The first difference decides the result. If one sequence is a prefix of the other, the shorter one is smaller.
print("apple" < "banana")
print([1, 2, 3] < [1, 3])
print((1, 2) < (1, 2, 0))
print([1, 2] == (1, 2))This prints True, True, True and False. A list never equals a tuple, even with the same items. Strings compare by Unicode code point, so "Z" < "a" is True.
Membership
in asks whether something is contained. What counts as contained depends on the type.
print("py" in "python")
print(3 in [1, 2, 3])
print([1, 2] in [[1, 2], [3]])
print("a" in {"a": 1})
print("a" not in "xyz")On a string, in checks for a substring of any length. On a list or tuple, it checks for an element equal to the value. On a dictionary, it checks the keys. Searching a list or tuple is linear, so use a set or dict for repeated lookups on large data.
Augmented assignment differs by type
+= and *= work on sequences, but lists handle them differently from tuples and strings.
a = [1, 2]
b = a
a += [3]
print(b)
t = (1, 2)
u = t
t += (3,)
print(u, t)For a list, += extends the existing object in place, so b also shows [1, 2, 3]. A tuple cannot change, so t += (3,) creates a new tuple and u stays (1, 2). In place, a += x behaves like a.extend(x). The a = a + x form builds a new list instead.
Exercise
What does [[1]] * 3 produce, and what happens to the other two inner lists after you run x = [[1]] * 3 and then x[0].append(2)?
Show answer
It produces [[1], [1], [1]], three references to one inner list. After x[0].append(2), all three show [1, 2], so x is [[1, 2], [1, 2], [1, 2]].