4. Data Structures & Comprehensions

Work efficiently with sequences and mappings; create new collections succinctly and readably.

Question: What are comprehensions?

Answer: A concise syntax for creating a list, dict, or set from an iterable. They are often more readable and faster than a traditional for loop.

evens = [n for n in range(10) if n % 2 == 0]
mapping = {c: c.upper() for c in "abc"}

Question: What's the difference between a list comprehension and a generator expression?

Answer: A list comprehension [... ] creates the entire list in memory at once. A generator expression (...) creates a generator object, which produces items one by one (lazily) as they are needed, making it more memory-efficient for large datasets.

Question: How do you sort a list of dictionaries by a specific key?

Answer: Use the sorted() function with a lambda function for the key argument.

users = [{"name": "Ada", "age": 30}, {"name": "Bob", "age": 25}]
sorted_users = sorted(users, key=lambda u: u["age"])

You can also use operator.itemgetter for readability:

from operator import itemgetter
sorted_users = sorted(users, key=itemgetter("age"))

Question: What set operations are commonly used?

Answer: Use | union, & intersection, - difference, ^ symmetric difference; methods like .issubset() and .issuperset() compare sets.

a, b = {1,2,3}, {3,4}
a | b  # {1,2,3,4}
a & b  # {3}

Question: What are useful dict methods?

Answer: .get() for safe access with default, .setdefault() to ensure a key exists, .update() to merge, .items()/.keys()/.values() return dynamic views.

counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

Question: list.append vs list.extend?

Answer: append(x) adds a single item; extend(iterable) adds all items from another iterable.

xs = [1]
xs.append([2,3])   # [1, [2,3]]
xs = [1]
xs.extend([2,3])   # [1, 2, 3]

Question: How do you merge dictionaries in modern Python?

Answer: Use | to produce a new dict and |= to update in place (Python 3.9+).

a = {"x": 1}
b = {"y": 2}
c = a | b        # {"x":1, "y":2}
a |= {"z": 3}   # a becomes {"x":1, "z":3}

Question: Can comprehensions include conditional expressions?

Answer: Yes—place the if/else in the expression, not the filter position.

labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]