Strings, Lists, Tuples and Dictionaries
Strings, Lists, Tuples and Dictionaries tests the built-in collection types: indexing and slicing, mutability, common methods, conversion between types, and the effect of aliasing.
Core rules
- Strings are ordered and immutable. Indexing starts at 0; negative indices count from the end. Slicing uses
[start:stop:step]and excludesstop. - String methods such as
upper(),lower(),strip(),split(),replace()andfind()return new values; they do not change the original string. - Lists are ordered and mutable. Methods include
append(),extend(),insert(),remove(),pop(),sort()andreverse(). - Tuples are ordered and immutable, written with parentheses. A one-element tuple needs a trailing comma:
(5,). - Dictionaries store key–value pairs. Keys must be unique and immutable; values can be anything. Use
get()to avoid a KeyError. list(),tuple()anddict()convert between types where the data fits.
Worked example
a = [10, 20, 30]
b = a
b.append(40)
print(a)
This prints [10, 20, 30, 40]. The assignment b = a copies the reference, not the list, so both names point to the same object. To make an independent copy, use b = a[:] or b = list(a). Similarly, 'COMPUTER'[2:5] gives 'MPU' because indices 2, 3 and 4 are included and 5 is excluded.
Traps that cost marks
- Trying
s[0] = 'X'on a string; strings are immutable. - Writing
(5)and expecting a tuple; it is just the integer 5. - Using
d['key']for a missing key instead ofd.get('key'). - Confusing
remove(value)withpop(index)in lists. - Assuming slicing includes the stop index.