Autocoder

Python List, Dict and Set Interview Questions

Last updated 2026-11-19

Lists, dictionaries and sets are the data structures behind almost every Python coding round. Interviewers ask about them in three ways: what an operation costs, what a short snippet prints, and which structure fits a given problem.

This page works through the operations and traps that come up most: slicing and aliasing, sort stability, dictionary ordering and merging, set algebra, and the time complexity you are expected to quote. Complexities refer to CPython.

LevelFresher to 2 years
FocusBuilt-in collections and their costs
VersionPython 3.9 and later

Complexity cheat sheet

Quote complexity with the word average or amortised where it applies, because hash operations degrade to O(n) in the worst case.

Where to go next

For algorithm practice on these structures see hashing interview questions and array interview questions. Broader preparation advice is in how to crack a Python interview.

Python List, Dict and Set Interview Questions: questions with worked answers

  1. 1

    What is the difference between a list, a tuple and a set?

    easy

    A list is an ordered, mutable sequence that allows duplicates. A tuple is an ordered, immutable sequence, usable as a dictionary key if its items are hashable. A set is an unordered, mutable collection of unique hashable items with fast membership tests. Pick a list for ordered data that changes, a tuple for fixed records, and a set for uniqueness and membership checks.

  2. 2

    How does slicing work? Predict the output.

    easy

    a[start:stop:step] returns a new list containing items from start up to but excluding stop. Negative indices count from the end, omitted bounds default to the ends, and slicing never raises IndexError for out-of-range bounds. A negative step walks backwards. Slicing makes a shallow copy.

    python
    a = [0, 1, 2, 3, 4, 5]
    print(a[1:4])      # [1, 2, 3]
    print(a[::-1])     # [5, 4, 3, 2, 1, 0]
    print(a[-2:])      # [4, 5]
    print(a[10:20])    # []
    print(a[::2])      # [0, 2, 4]
  3. 3

    Why does [[0]*3]*3 behave unexpectedly, and how do you build a proper grid?

    medium

    Multiplying a list repeats references to the same inner list, so all three rows are one object. Changing one row changes all of them. Build each row separately with a comprehension.

    python
    g = [[0] * 3] * 3
    g[0][0] = 1
    print(g)     # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
    
    g = [[0] * 3 for _ in range(3)]
    g[0][0] = 1
    print(g)     # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
  4. 4

    What is the difference between append, extend and insert, and between remove, pop and del?

    medium

    append adds one object at the end, even if it is a list. extend adds each item of an iterable. insert(i, x) adds at a position and costs O(n). remove(x) deletes the first matching value and raises ValueError if absent. pop(i) removes and returns the item at i, defaulting to the last, in O(1) for the end. del a[i] or del a[i:j] removes by position or slice without returning anything.

    python
    a = [1, 2]
    a.append([3, 4])
    print(a)        # [1, 2, [3, 4]]
    a = [1, 2]
    a.extend([3, 4])
    print(a)        # [1, 2, 3, 4]
  5. 5

    What does sort return, and how do sorted and key work? Is sorting stable?

    medium

    list.sort() sorts in place and returns None, a classic bug when written as a = a.sort(). sorted(iterable) returns a new list from any iterable. Both accept key, a function applied once per element, and reverse. Python's Timsort is stable, so equal keys keep their original relative order, which lets you sort by several fields in successive passes.

    python
    words = ["bb", "a", "ccc", "dd"]
    print(sorted(words, key=len))             # ['a', 'bb', 'dd', 'ccc']
    print(sorted(words, key=len, reverse=True))  # ['ccc', 'bb', 'dd', 'a']
    x = [3, 1, 2].sort()
    print(x)                                  # None
  6. 6

    Predict the output: modifying a list while iterating over it.

    hard

    The loop uses an internal index. Removing an item shifts later items left, so the iterator skips the element that moved into the removed slot. Iterate over a copy, or build a new list with a comprehension.

    python
    a = [1, 2, 2, 3]
    for x in a:
        if x == 2:
            a.remove(x)
    print(a)          # [1, 2, 3]
    
    a = [1, 2, 2, 3]
    a = [x for x in a if x != 2]
    print(a)          # [1, 3]
  7. 7

    How do you remove duplicates from a list while keeping order?

    easy

    set() removes duplicates but loses order for the general case. Since dictionaries preserve insertion order from Python 3.7, dict.fromkeys(a) deduplicates and keeps first occurrences in O(n). For unhashable items, track seen items with a linear scan.

    python
    a = [3, 1, 3, 2, 1]
    print(list(dict.fromkeys(a)))   # [3, 1, 2]
    print(list(set(a)))             # order not guaranteed
  8. 8

    How do dictionaries work internally, and what is the lookup complexity?

    medium

    A dict is a hash table. Python computes hash(key), maps it to a slot in an index table, resolves collisions by open addressing, and compares keys by identity first and then equality. Lookup, insert and delete are O(1) on average and O(n) in the worst case with many collisions. Since Python 3.7 insertion order is part of the language guarantee. The table resizes as it fills, so single inserts are amortised O(1).

  9. 9

    What is the difference between dict.get, [] access and setdefault? When would you use defaultdict?

    medium

    d[k] raises KeyError if the key is missing. d.get(k, default) returns the default without inserting. d.setdefault(k, v) returns the existing value or inserts v and returns it. collections.defaultdict(factory) calls the factory automatically for missing keys, which is the cleanest way to group or count.

    python
    from collections import defaultdict, Counter
    groups = defaultdict(list)
    for w in ["tea", "eat", "ten"]:
        groups["".join(sorted(w))].append(w)
    print(dict(groups))     # {'aet': ['tea', 'eat'], 'ent': ['ten']}
    print(Counter("banana").most_common(2))  # [('a', 3), ('n', 2)]
  10. 10

    How do you merge two dictionaries in modern Python?

    medium

    From Python 3.9, use the union operator: a | b returns a new dict and a |= b updates in place, with the right side winning on duplicate keys. Earlier, dict unpacking inside braces does the same (see the second print below). a.update(b) mutates a. All of these are shallow, so nested dicts are not merged recursively.

    python
    a = {"x": 1, "y": 2}
    b = {"y": 20, "z": 30}
    print(a | b)        # {'x': 1, 'y': 20, 'z': 30}
    print({**b, **a})   # {'y': 2, 'z': 30, 'x': 1}
  11. 11

    Predict the output: what happens when you change a dict's size during iteration?

    hard

    Adding or deleting keys while iterating over a dict raises RuntimeError: dictionary changed size during iteration. Updating the value of an existing key is allowed. To delete while looping, iterate over list(d) or build a new dict with a comprehension.

    python
    d = {"a": 1, "b": 2, "c": 3}
    for k in list(d):
        if d[k] % 2:
            del d[k]
    print(d)            # {'b': 2}
  12. 12

    What are the main set operations, and how do you write them?

    easy

    Union a | b, intersection a & b, difference a - b and symmetric difference a ^ b, each with a method form such as a.union(b). Sets also support subset tests with <= and isdisjoint. Operations on two sets of sizes m and n cost about O(m + n) for union and O(min(m, n)) for intersection on average.

    python
    a, b = {1, 2, 3}, {2, 3, 4}
    print(a | b, a & b, a - b, a ^ b)
    # {1, 2, 3, 4} {2, 3} {1} {1, 4}
    print({} == set(), type({}))     # False <class 'dict'>
  13. 13

    Why is checking membership in a set faster than in a list, and how can that fix a slow loop?

    medium

    x in list scans items one by one, O(n). x in set hashes x and checks a slot, O(1) on average. Replacing a list of lookups with a set turns a nested-loop O(n*m) solution into O(n+m). The set needs O(n) space and its items must be hashable.

    python
    allowed = set(range(0, 1_000_000, 3))
    hits = [x for x in range(1000) if x in allowed]   # fast
    print(len(hits))     # 334
  14. 14

    What is the difference between a list comprehension, a dict comprehension and a set comprehension?

    medium

    They share the same syntax with different brackets: [expr for x in it if cond] builds a list, {k: v for ...} a dict and {expr for ...} a set. Dict and set comprehensions drop duplicates by key or value. A comprehension has its own scope in Python 3, so its loop variable does not leak.

    python
    nums = [1, 2, 3, 4]
    print({n: n * n for n in nums if n % 2 == 0})   # {2: 4, 4: 16}
    print({n % 2 for n in nums})                    # {0, 1}
  15. 15

    Predict the output: sorting a list of tuples and sorting dictionary items by value.

    hard

    Tuples compare element by element, so sorted() on a list of tuples sorts by the first element then the second. To sort a dictionary by value, sort its items with a key and rebuild a dict, which keeps the sorted insertion order. Use a negative value or reverse=True for descending order.

    python
    d = {"a": 3, "b": 1, "c": 3}
    print(sorted(d.items(), key=lambda kv: kv[1]))
    # [('b', 1), ('a', 3), ('c', 3)]
    print(dict(sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))))
    # {'a': 3, 'c': 3, 'b': 1}
  16. 16

    When would you use a deque or heapq instead of a list?

    medium

    Removing from the front of a list is O(n) because items shift, so a queue built on list.pop(0) is slow. collections.deque gives O(1) append and popleft at both ends. heapq maintains a min-heap inside a plain list with O(log n) push and pop and O(1) peek at index 0, ideal for top-k and scheduling problems. Use heapq.nlargest(k, data) for a quick top-k.

    python
    import heapq
    h = []
    for x in [5, 1, 4]:
        heapq.heappush(h, x)
    print(heapq.heappop(h), h[0])   # 1 4

Frequently asked questions

Are Python sets ordered?

No. A set has no defined order and you cannot index it. Dictionaries, by contrast, preserve insertion order from Python 3.7.

What is the time complexity of list.append?

O(1) amortised. Occasionally the underlying array is resized, which costs O(n), but this averages out across many appends.

Can a tuple be a dictionary key?

Yes, if every element inside it is hashable. A tuple that contains a list is not hashable and raises TypeError.

How do I copy a list safely?

Use a.copy(), list(a) or a[:] for a shallow copy. Use copy.deepcopy when the list contains mutable items you also want independent.

Related guides

More in Programming Language Interview Questions by Language

See all in this section