Pick the structure that fits each need: immutable tuples, sets for O(1) membership tests, Counter and defaultdict for recurring patterns.
Open this lesson in KodokonChoosing the right data structure settles both readability and performance in one move. The tuple is an immutable sequence: ideal for a fixed-size heterogeneous record (coordinates, a key-value pair). Immutable implies hashable (if its contents are): a tuple can therefore serve as a dictionary key or a set element, which a list cannot. Unpacking makes code expressive - and a function that "returns several values" actually returns a tuple.
point = (48.85, 2.35)
lat, lon = point
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high)
distances = {("paris", "lyon"): 465}
print(distances[("paris", "lyon")])The set guarantees uniqueness and offers a membership test in O(1) on average, where a list is O(n). In a loop that checks x in collection thousands of times, the difference shows up immediately. Set operators (& intersection, - difference, | union) are a real upgrade over nested loops: comparing two lists of identifiers - who disappeared, who is new - fits in two lines.
active = {"ada", "linus", "guido"}
banned = {"linus", "mallory"}
print(active & banned)
print(active - banned)
print(active | banned)
emails = ["a@x.io", "b@x.io", "a@x.io"]
unique = set(emails)
print(len(unique))The collections module covers two everyday needs. Counter counts the occurrences in an iterable and exposes most_common(n) - no more hand-written counting dictionaries. defaultdict(factory) builds the missing value on the fly: defaultdict(list) is the canonical tool for grouping elements by key without testing the key's existence on every pass of the loop.
from collections import Counter, defaultdict
words = ["go", "py", "go", "rs", "go"]
counts = Counter(words)
print(counts.most_common(2))
groups = defaultdict(list)
pairs = [("fr", "Ada"), ("us", "Lin"), ("fr", "Zoe")]
for country, name in pairs:
groups[country].append(name)
print(dict(groups))