Skip to main content
LIVE CONTEST: Round #7 · Begin Marathon is live now! …

~/algor $ cat blog/python-royxat-lugat-toplam

Python Lists and Dictionaries: list, tuple, dict and set in Practice

When do you need list, tuple, dict and set in Python? Operation complexity, comprehensions, Counter and defaultdict, sorting with key= and two-sum with a dict.

Python Views: 24
@iqbolshoh
Python Lists and Dictionaries: list, tuple, dict and set in Practice — cover image
When do you need list, tuple, dict and set in Python? Operation complexity, comprehensions, Counter and defaultdict, sorting with key= and two-sum with a dict.

When a Python solution gets TLE (Time Limit Exceeded), the culprit is often not the language but the wrong container. The expression x in a checks a list element by element, while a set answers instantly. $10^5$ such queries on a list of $10^5$ elements mean $10^{10}$ operations, and the time limit is certain to be exceeded.

In this article we look at the four core containers — list, tuple, dict and set: when each one is needed, what their complexity is, and which handy tools the collections module offers.


1. The complexity table

A list is a dynamic array, while a dictionary (dict) and a set are built on a hash table. The whole difference follows from that:

Operation list dict / set
a[i], d[key] $O(1)$ $O(1)$ on average
append, add $O(1)$ $O(1)$ on average
insert(0, x), pop(0) $O(N)$ —
x in ... $O(N)$ $O(1)$ on average
sort() $O(N \log N)$ —

If you often need to take elements from the front, use collections.deque: its popleft() runs in $O(1)$.


2. list and tuple

A list is mutable, a tuple is immutable. That is why a tuple can be hashed: it can be a dictionary key or a set element, whereas a list cannot. For building lists, a comprehension ([... for ... if ...]) is shorter than a plain loop and usually faster.

a = [5, 3, 8, 1]
a.append(10)                      # append to the end: O(1)
a.sort()                          # in-place sort: O(N log N)
print(a)                          # [1, 3, 5, 8, 10]

odd_sq = [x * x for x in a if x % 2 == 1]
print(odd_sq)                     # [1, 9, 25]

grid = [[0] * 3 for _ in range(2)]  # every row is its own list
grid[0][0] = 1
print(grid)                       # [[1, 0, 0], [0, 0, 0]]

dist = {(2, 3): 5}                # a tuple can be a dict key
print(dist[(2, 3)], len(set([1, 2, 2, 3])))  # 5 3

A classic trap: [[0] * 3] * 2 does not create a two-row table — both rows point to the same list, and grid[0][0] = 1 changes both at once. Meanwhile len(set(a)) gives the number of distinct elements.


3. dict, set and Counter

A dictionary maps keys to values and, since Python 3.7, keeps insertion order. Reading a missing key with d[key] raises KeyError, so d.get(key, 0) is handy. Sets support a & b (intersection), a | b (union) and a - b (difference).

For counting problems Counter is the most convenient tool. The program below counts word frequencies and uses key= to sort the result by two criteria:

import sys
from collections import Counter

words = sys.stdin.read().split()
cnt = Counter(words)
order = sorted(cnt.items(), key=lambda p: (-p[1], p[0]))  # most frequent first, ties in alphabetical order
for w, k in order:
    print(w, k)

Given olma nok olma uzum nok olma, the program prints olma 3, nok 2, uzum 1. -p[1] gives descending order, and p[0] puts ties in alphabetical order.


4. defaultdict: grouping

defaultdict creates the initial value for a new key itself, so no if key not in d check is needed. When grouping anagrams, the key is the word's letters in sorted order:

from collections import defaultdict

words = ["eat", "tea", "tan", "ate", "nat", "bat"]
groups = defaultdict(list)        # a new key starts as []
for w in words:
    groups["".join(sorted(w))].append(w)
for key in sorted(groups):
    print(key, groups[key])

The result: abt ['bat'], aet ['eat', 'tea', 'ate'], ant ['tan', 'nat'].


5. A worked problem: two-sum

Find the indices of two array elements whose sum equals target. The naive solution tries every pair — $O(N^2)$, which is about $5 \cdot 10^9$ pairs for $N = 10^5$. The key observation: for each $x$ we need exactly target - x. If we keep the values seen so far in a dictionary, that check takes $O(1)$ and the whole solution becomes $O(N)$.

def two_sum(a, target):
    seen = {}                     # value -> index
    for j, x in enumerate(a):
        if target - x in seen:    # O(1) on average
            return seen[target - x], j
        seen[x] = j
    return None

print(two_sum([2, 7, 11, 15], 9))  # (0, 1)
print(two_sum([3, 2, 4], 6))       # (1, 2)
print(two_sum([1, 2], 7))          # None

Conclusion

For lookups and counting use dict and set, for order and indices use list, and for a pair used as a key use tuple. Choosing the right container often removes a TLE without changing the algorithm itself. Put these rules to the test on the array problems and string problems!

Was it useful? Share it with friends:
Telegram

Related articles

All articles →