Full answer
python
import timeit
from collections import Counter, defaultdict, deque
big_list = list(range(100_000)); big_set = set(big_list)
t_list = timeit.timeit(lambda: 99_999 in big_list, number=200)
t_set = timeit.timeit(lambda: 99_999 in big_set, number=200)
print("set faster:", t_set < t_list)
words = ["pen", "ink", "pen", "pad", "ink", "pen"]
print(Counter(words).most_common(2))
groups = defaultdict(list)
for w in words: groups[len(w)].append(w)
print(dict(groups))
q = deque([1, 2, 3]); q.appendleft(0); q.pop(); print(q)
print(list(dict.fromkeys(words)))Output:
text
set faster: True
[('pen', 3), ('ink', 2)]
{3: ['pen', 'ink', 'pen', 'pad', 'ink', 'pen']}
deque([0, 1, 2])
['pen', 'ink', 'pad']Membership in a set is a hash lookup, while in a list it is a scan, which is why checking 'x in big_list' inside a loop can turn a fast program slow. The run shows the results only as True or False so the output does not depend on machine speed.
Task to structure:
- Counting things:
collections.Counter, a dict subclass. - Grouping:
collections.defaultdict(list). - Queue or sliding window:
collections.dequewithappendandpopleft, both O(1);list.pop(0)is O(n). - Unique values preserving order:
list(dict.fromkeys(items)). - Priority queue:
heapqon a list. - Fixed records: tuples or dataclasses.
Dicts preserve insertion order since Python 3.7, which the Counter and fromkeys outputs reflect.
python
import timeit
from collections import Counter, defaultdict, deque
big_list = list(range(100_000)); big_set = set(big_list)
t_list = timeit.timeit(lambda: 99_999 in big_list, number=200)
t_set = timeit.timeit(lambda: 99_999 in big_set, number=200)
print("set faster:", t_set < t_list)
words = ["pen", "ink", "pen", "pad", "ink", "pen"]
print(Counter(words).most_common(2))
groups = defaultdict(list)
for w in words: groups[len(w)].append(w)
print(dict(groups))
q = deque([1, 2, 3]); q.appendleft(0); q.pop(); print(q)
print(list(dict.fromkeys(words)))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- list, tuple, dict and set cover most needs
- Sets and dicts give O(1) average lookups
- deque for both-end operations
- Counter and defaultdict simplify counting and grouping
- Dicts keep insertion order
Common mistakes
- Membership tests on large lists in loops
- Using list.pop(0) as a queue
Follow-ups
- How is a dict implemented?
- When would you use heapq?
Tips
- Match structure to the main operation