Data Structures and Strings: Lists, Dictionaries, Iteration, and Manipulation
Arrays/lists, dictionaries/maps, and strings are the containers that hold most program data. The exam checks indexing, slicing, mutation, lookup semantics, and whether you can pick the right structure - a list for order, a dictionary for keyed lookup, a set for membership.
Lists and arrays
Indices are zero-based; negative indices count from the end in Python. Slicing a[start:stop] includes start and excludes stop, so a[0:3] gives three elements. append adds one item, extend adds each item of an iterable, and + creates a new list. sort() sorts in place and returns None; sorted() returns a new list.
Dictionaries and maps
A dictionary stores key–value pairs with average O(1) lookup. Accessing a missing key with d[k] raises KeyError; d.get(k, default) returns a default instead. Keys must be hashable, which excludes lists. Iterating a dictionary yields keys by default; use .items() for pairs. Since Python 3.7 insertion order is preserved, but you should not rely on dictionaries being sorted.
Strings
Strings are immutable sequences of characters. s[0] = 'H' fails; build a new string instead. Useful methods include split, join, strip, replace, lower, startswith, and find. ''.join(parts) is the efficient way to concatenate many pieces, since repeated + in a loop creates a new string each time.
Worked example
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
b = a copies the reference, not the list, so both names point at the same object. Use b = a.copy() or b = a[:] for a shallow copy, and copy.deepcopy for nested structures.
Traps
- Index out of range at
len(a)- the last valid index islen(a) - 1. - Off-by-one in slices, since the stop index is excluded.
- Mutating a collection while iterating over it.
- Expecting
sort()to return the sorted list. - Expecting
d[k]to returnNonefor a missing key instead of raising.