Python for AI Engineers · Part A · Lesson 3 of 26

Python lists, dicts, sets and tuples: when to use each

The four built-in collections for a Java or JavaScript developer: list costs (Big-O), dict lookups and defaults, sets for fast membership and dedupe, tuples as keys, comprehensions, Counter, defaultdict, deque, sorting with key=, and copy versus alias.

⏱ 40 min3 exercises that check your codeRuns in your browser

By the end you can

  • Use lists, dicts, sets and tuples, and know which operations are fast (O(1)) and which are slow (O(n))
  • Read missing dict keys safely with get and setdefault, and sort anything with key= and a lambda
  • Build collections in one line with list, dict and set comprehensions
  • Reach for Counter, defaultdict and deque, and tell a copy from an alias (shallow versus deep)
  • Pick the right structure for real AI tasks: dedupe chunks, count tokens per user, group documents by source
1 / 6

1Lists: Python's ArrayList

A list is an ordered, growable array, written with square brackets. It is the same idea as ArrayList in Java or an array in JavaScript, and it can hold any mix of values.

What matters is the cost of each operation. Adding or removing at the end is fast, O(1). Adding or removing at the front moves every other item one slot, so it is O(n): it gets slower as the list grows. Reading by index (messages[3]) is O(1). Checking x in my_list walks the list item by item until it finds a match, so it is O(n) too.

Quick reference: append(x) adds one item, extend(other) adds every item of another list, insert(i, x) puts x at position i, pop() removes and returns the last item, pop(0) the first one, index(x) finds a position and count(x) counts matches. len(my_list) gives the size (there is no .length or .size()).

Try it: edit and run
messages = ["system: be brief", "user: hi"]

messages.append("assistant: hello")      # add to the end: fast, O(1)
messages.insert(0, "note: test run")     # add at the front: shifts every item, O(n)
print(len(messages))
print(messages[0])                       # first item
print(messages[-1])                      # last item (negative counts from the end)

last = messages.pop()                    # remove from the end: O(1)
first = messages.pop(0)                  # remove from the front: O(n)
print(last, "|", first)

print("user: hi" in messages)            # scans the list: O(n)
print(messages.index("user: hi"))        # position of the first match
messages.extend(["user: bye", "user: bye"])
print(messages.count("user: bye"), messages)
Expected output
4
note: test run
assistant: hello
assistant: hello | note: test run
True
1
2 ['system: be brief', 'user: hi', 'user: bye', 'user: bye']
Java
List<String> messages = new ArrayList<>(List.of("system: be brief", "user: hi"));
messages.add("assistant: hello");        // O(1) at the end
messages.add(0, "note: test run");       // O(n) at the front
messages.size();                         // 4
messages.contains("user: hi");           // O(n) scan
JavaScript
const messages = ["system: be brief", "user: hi"];
messages.push("assistant: hello");       // O(1) at the end
messages.unshift("note: test run");      // O(n) at the front
messages.length;                         // 4
messages.includes("user: hi");           // O(n) scan

Tip A chat history grows at the end, so append is perfect for it. If you keep removing from the front (a queue of jobs, a sliding window of recent turns), use deque from section 7 instead.

2Sorting with key= and lambda

sorted(items) returns a new sorted list and leaves the original alone. items.sort() sorts the list in place and returns None. Both take the same two options: reverse=True for high to low, and key= for what to sort by.

key= is a function that receives one item and returns the value to compare, like a Comparator.comparing(...) in Java. lambda c: c["score"] is a tiny one-expression function, the Python version of the arrow function c => c.score. Return a tuple from the key to sort by several things: Python compares tuples item by item, so the second item only matters when the first ones tie.

Python's sort is stable: items that compare equal keep their original order. min and max take key= too.

Try it: edit and run
chunks = [
    {"text": "Returns within 30",   "score": 0.71, "source": "policy.md"},
    {"text": "Shipping is free",    "score": 0.93, "source": "home.md"},
    {"text": "Refunds take 5 days", "score": 0.71, "source": "faq.md"},
]

best = sorted(chunks, key=lambda c: c["score"], reverse=True)   # a new list
print([c["source"] for c in best])        # ties keep their original order

# score high to low, then source A to Z when scores tie
best = sorted(chunks, key=lambda c: (-c["score"], c["source"]))
print([c["source"] for c in best])

names = ["bob", "alice", "Carol"]
names.sort()                 # in place; capital letters sort first
print(names)
names.sort(key=str.lower)    # any one-argument function can be the key
print(names)

top = max(chunks, key=lambda c: c["score"])
print(top["text"])
Expected output
['home.md', 'policy.md', 'faq.md']
['home.md', 'faq.md', 'policy.md']
['Carol', 'alice', 'bob']
['alice', 'bob', 'Carol']
Shipping is free
Java
chunks.sort(Comparator
    .comparingDouble((Chunk c) -> c.score()).reversed()
    .thenComparing(Chunk::source));
JavaScript
chunks.sort((a, b) =>
  b.score - a.score || a.source.localeCompare(b.source));

What the key lines do

  • key=lambda c: c["score"] means: for each chunk c, compare by its score.
  • [c["source"] for c in best] is a list comprehension (section 6): it makes a list of the sources.
  • -c["score"]: the minus sign flips the score so high scores come first, while the source still sorts A to Z.

Watch out results = results.sort() sets results to None, because .sort() changes the list in place and returns nothing. Write results.sort() on its own line, or results = sorted(results).

3Dicts: key to value, in insertion order

A dict maps keys to values, like a Java HashMap or a JavaScript object or Map. Reading, writing and checking a key with in are all O(1) on average, because a dict is a hash table. Since Python 3.7 a dict also remembers insertion order, so it behaves like Java's LinkedHashMap.

d["key"] raises KeyError when the key is missing (JavaScript would give you undefined). When a key may be absent, use d.get("key") for None, or d.get("key", default) for your own fallback. Loop over d.items() to get each key and value together.

d.setdefault(key, []) returns the value for key, first storing [] if the key is missing. It is the one-liner for "make the list the first time, then keep adding to it".

Try it: edit and run
config = {"model": "llama3.2:3b", "temperature": 0.2}
config["max_tokens"] = 256                 # add a key
print(list(config))                        # keys come back in insertion order

print(config.get("timeout"))               # missing key: None, no error
print(config.get("timeout", 30))           # or the default you pass
try:
    config["timeout"]
except KeyError as e:
    print("KeyError:", e)

for key, value in config.items():          # key and value together
    print(f"{key} = {value}")

by_user = {}
by_user.setdefault("asha", []).append("hi")      # creates the list the first time
by_user.setdefault("asha", []).append("thanks")  # reuses it after that
print(by_user)
print("model" in config)                   # checks the keys, O(1)
removed = config.pop("temperature")        # remove a key and get its value
print(removed, config)
Expected output
['model', 'temperature', 'max_tokens']
None
30
KeyError: 'timeout'
model = llama3.2:3b
temperature = 0.2
max_tokens = 256
{'asha': ['hi', 'thanks']}
True
0.2 {'model': 'llama3.2:3b', 'max_tokens': 256}

What the key lines do

  • list(config) gives the keys only. Use config.values() for the values and config.items() for pairs.
  • for key, value in ... unpacks each (key, value) tuple into two names (more on unpacking in section 5).

Tip A JSON reply from a model is parsed into dicts and lists. Read optional fields with .get(): reply.get("usage", {}).get("total_tokens", 0) never crashes when the server leaves usage out.

4Sets: fast membership and dedupe

A set is an unordered collection of unique values, like Java's HashSet or JavaScript's Set. Adding a value that is already there does nothing. The big win: x in my_set is a hash lookup, O(1) on average, while x in my_list is a scan, O(n). With 100,000 chunk ids that is the difference between one step and up to 100,000.

set(items) removes duplicates, but a set has no order, so you lose the original order. To dedupe and keep the order of first appearance, use list(dict.fromkeys(items)): dict keys are unique and keep insertion order.

Sets support math directly: & (in both), | (in either), - (in the left one only) and ^ (in exactly one). That is how you compare the documents your search returned with the ones it should have returned.

Try it: edit and run
seen = {"doc-1", "doc-2"}
seen.add("doc-3")
seen.add("doc-1")                 # already there: nothing happens
print(len(seen), "doc-2" in seen)  # membership is a hash lookup, O(1)

tags = ["python", "ai", "python", "rag", "ai"]
print(sorted(set(tags)))          # dedupe; a set has no order, so sort to print
print(list(dict.fromkeys(tags)))  # dedupe and keep the first-seen order

retrieved = {"doc-1", "doc-2", "doc-3"}
relevant = {"doc-2", "doc-3", "doc-9"}
print(sorted(retrieved & relevant))   # in both (intersection)
print(sorted(retrieved | relevant))   # in either (union)
print(sorted(retrieved - relevant))   # in retrieved only (difference)
print(sorted(retrieved ^ relevant))   # in exactly one (symmetric difference)

empty = set()                     # {} would be an empty dict, not a set
print(type(empty).__name__, type({}).__name__)
Expected output
3 True
['ai', 'python', 'rag']
['python', 'ai', 'rag']
['doc-2', 'doc-3']
['doc-1', 'doc-2', 'doc-3', 'doc-9']
['doc-1']
['doc-1', 'doc-9']
set dict

len(retrieved & relevant) / len(relevant) is recall (here 2 / 3): the share of the right documents your search found. You will compute it exactly like this in the evals lab.

Watch out Printing a set of strings directly can show a different order on every run, because string hashes are randomised per process. Never rely on set order; sorted() it when you print or compare.

5Tuples: fixed records, unpacking, and dict keys

A tuple is like a list that cannot change after it is created, written with round brackets: (0.12, -0.53). Use it for a small fixed group of values that belong together, such as a (text, score) pair, a 2D point, or a (model, prompt) pair.

Unpacking assigns each item to its own name: text, score = result. A function that "returns two values" is really returning one tuple, and the caller unpacks it. first, *rest = items puts the first item in first and the rest in a list, a bit like const [first, ...rest] = items in JavaScript.

Because tuples cannot change, they are hashable: they can be dict keys and set items. Lists cannot. A (model, prompt) tuple is a natural cache key.

Try it: edit and run
point = (0.12, -0.53)            # a tuple: fixed size, cannot change
try:
    point[0] = 1.0
except TypeError as e:
    print("TypeError:", e)

x, y = point                     # unpacking: one name per item
print(x, y)

def search(query):
    return "Refunds take 5 days", 0.91   # returning two values = returning a tuple

text, score = search("refund?")
print(text, score)

first, *rest = ["system", "user", "assistant"]   # * collects the rest into a list
print(first, rest)

single = ("only",)               # one item needs the trailing comma
print(type(single).__name__, type(("only")).__name__)

# tuples are hashable, so they can be dict keys and set items; lists cannot
cache = {("llama3.2:3b", "What is DNS?"): "It maps names to IPs."}
print(cache[("llama3.2:3b", "What is DNS?")])
try:
    cache[["llama3.2:3b", "What is DNS?"]] = "nope"
except TypeError as e:
    print("TypeError:", e)
Expected output
TypeError: 'tuple' object does not support item assignment
0.12 -0.53
Refunds take 5 days 0.91
system ['user', 'assistant']
tuple str
It maps names to IPs.
TypeError: unhashable type: 'list'

What the key lines do

  • return "Refunds take 5 days", 0.91: the comma makes the tuple, not the brackets: return a, b is the same as return (a, b).
  • ("only") is just a string in brackets. A one-item tuple needs the comma: ("only",).

Tip A tuple is only frozen one level deep: (1, [2, 3]) cannot get a new item, but the list inside it can still change, and such a tuple is not hashable. Keep dict-key tuples made of strings, numbers and other tuples.

6Comprehensions: build a collection in one line

A comprehension builds a new list, dict or set from a loop, with an optional filter. Read [d.strip() for d in docs if d.strip()] as: "for each d in docs, if d.strip() is not empty, keep d.strip()". It replaces JavaScript's docs.filter(...).map(...) and Java's stream().filter().map().toList().

Square brackets make a list, {key: value for ...} makes a dict, and {value for ...} makes a set. Several for clauses read left to right like nested loops. Without any brackets, inside a call like sum(...), it becomes a generator expression: it yields one value at a time and never builds the whole list.

Try it: edit and run
docs = ["  Refunds take 5 days ", "", "Shipping is free", "   "]

clean = [d.strip() for d in docs if d.strip()]          # list comprehension
print(clean)

lengths = {d: len(d) for d in clean}                     # dict comprehension
print(lengths)

words = {w.lower() for d in clean for w in d.split()}    # set comprehension, two loops
print(sorted(words))

pairs = [(i, d) for i, d in enumerate(clean, start=1)]
print(pairs)

total = sum(len(d) for d in clean)     # no brackets: a generator, nothing stored
print(total)
Expected output
['Refunds take 5 days', 'Shipping is free']
{'Refunds take 5 days': 19, 'Shipping is free': 16}
['5', 'days', 'free', 'is', 'refunds', 'shipping', 'take']
[(1, 'Refunds take 5 days'), (2, 'Shipping is free')]
35
Java
List<String> clean = docs.stream()
    .map(String::strip)
    .filter(d -> !d.isEmpty())
    .toList();
JavaScript
const clean = docs
  .map((d) => d.trim())
  .filter((d) => d.length > 0);

What the key lines do

  • d.strip() removes spaces at both ends. An empty string counts as false, so blank documents are dropped.
  • Two for clauses: the outer loop over documents comes first, the inner loop over words second.

Tip If a comprehension no longer fits on one readable line, or needs an else branch and a nested loop, write a normal for loop. Clear beats clever.

7collections: Counter, defaultdict and deque

The standard library module collections has three structures you will use constantly. from collections import Counter works like a Java import: it brings those names into your file.

Counter is a dict that counts. Give it any list and it counts each value; a missing key reads as 0 instead of raising KeyError, and most_common(n) gives the top n. defaultdict(list) is a dict that calls list() to create an empty list the first time you touch a missing key, so grouping needs no if key not in d check. deque ("deck") is a double-ended queue with O(1) adds and removes at both ends, like Java's ArrayDeque; with maxlen=n it keeps only the newest n items.

Try it: edit and run
from collections import Counter, defaultdict, deque

# Counter: a dict that counts
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(2))
print(counts["the"], counts["dog"])       # a missing key counts as 0, no KeyError
counts.update(["cat", "cat"])              # add more counts
print(counts["cat"])

# defaultdict: a dict that creates missing values for you
by_source = defaultdict(list)              # list is called to make each new value
for source, chunk in [("faq.md", "c1"), ("home.md", "c2"), ("faq.md", "c3")]:
    by_source[source].append(chunk)        # no "if source not in by_source" needed
print(dict(by_source))

# deque: a double-ended queue, O(1) at both ends
history = deque(maxlen=3)                  # keeps only the newest 3 items
for turn in ["t1", "t2", "t3", "t4"]:
    history.append(turn)                   # t1 falls off the left when t4 arrives
print(list(history))
history.appendleft("t0")                   # O(1) at the front; full, so t4 falls off the right
print(list(history))
print(history.popleft())                   # take from the front, also O(1)
Expected output
[('the', 3), ('and', 2)]
3 0
3
{'faq.md': ['c1', 'c3'], 'home.md': ['c2']}
['t2', 't3', 't4']
['t0', 't2', 't3']
t0

What the key lines do

  • Pass the function list itself, without brackets. defaultdict(int) would start missing keys at 0 instead.
  • dict(...) turns it back into a plain dict, only so that it prints neatly.
  • A deque with maxlen is the simplest "keep the last N chat turns" memory for a chatbot.

Watch out Reading a missing key from a defaultdict creates it: if by_source["x"]: quietly adds "x": []. To only check, use "x" in by_source.

8Copy or alias? Shallow and deep copies

Assignment never copies in Python, exactly like object references in Java and JavaScript. alias = base gives the same list a second name, so a change through either name shows up in both.

A shallow copy (list(base), base.copy(), base[:], dict(d), d.copy()) makes a new outer container, but the items inside are the same objects. A list of dicts copied this way still shares every dict. copy.deepcopy(base) copies everything, all the way down. is tells you whether two names point at the same object.

Try it: edit and run
import copy

base = [{"role": "system", "content": "Be brief."}]

alias = base                      # no copy: two names, one list
alias.append({"role": "user", "content": "hi"})
print(len(base))                  # 2: base changed too

shallow = list(base)              # new outer list, same dicts inside
shallow.append({"role": "user", "content": "bye"})
shallow[0]["content"] = "Be rude."    # edits the dict both lists share
print(len(base), base[0]["content"])

base[0]["content"] = "Be brief."
deep = copy.deepcopy(base)        # copies the dicts too
deep[0]["content"] = "Be rude."
print(base[0]["content"], "|", deep[0]["content"])

print(alias is base, shallow is base, shallow[0] is base[0], deep[0] is base[0])
Expected output
2
2 Be rude.
Be brief. | Be rude.
True False True False

What the key lines do

  • shallow[0]["content"] = ...: the append to shallow did not reach base (they are separate outer lists), but this edit does, because shallow[0] and base[0] are the same dict.
  • copy.deepcopy is slower and uses more memory. Use it only when you will change nested items.

Watch out A shared "system prompt" template list that every request copies with list(...) and then edits inside: one user's request changes the template for everyone. Build fresh dicts per request, or deep copy.

9Choosing the right structure for AI tasks

The rule of thumb: list when order matters and you mostly add at the end; dict to look things up by a key; set to ask "have I seen this?" and to dedupe; tuple for a small fixed record or a compound key; Counter to count; defaultdict(list) to group; deque for a queue or a "last N" window.

Here are three jobs from a real RAG pipeline. Dedupe retrieved chunks by text: a set of seen texts plus a list for the order. Count tokens per user for billing: a Counter. Group chunks by source document to show citations: a defaultdict(list).

Try it: edit and run
from collections import Counter, defaultdict

chunks = [
    {"id": "c1", "user": "asha", "source": "faq.md",  "text": "Refunds take 5 days", "tokens": 5},
    {"id": "c2", "user": "ben",  "source": "home.md", "text": "Shipping is free",    "tokens": 4},
    {"id": "c3", "user": "asha", "source": "faq.md",  "text": "Refunds take 5 days", "tokens": 5},
    {"id": "c4", "user": "asha", "source": "policy.md", "text": "Returns within 30", "tokens": 4},
]

# 1. Dedupe chunks by text, keep the first one: a set of what we have seen
seen, unique = set(), []
for c in chunks:
    if c["text"] not in seen:
        seen.add(c["text"])
        unique.append(c)
print([c["id"] for c in unique])

# 2. Count tokens per user: a Counter (a dict of numbers)
tokens = Counter()
for c in chunks:
    tokens[c["user"]] += c["tokens"]
print(tokens.most_common())

# 3. Group documents by source: a defaultdict(list)
by_source = defaultdict(list)
for c in unique:
    by_source[c["source"]].append(c["id"])
print(dict(by_source))
Expected output
['c1', 'c2', 'c4']
[('asha', 14), ('ben', 4)]
{'faq.md': ['c1'], 'home.md': ['c2'], 'policy.md': ['c4']}

What the key lines do

  • Multiple assignment: seen becomes an empty set and unique an empty list.
  • This check is O(1) because seen is a set. With a list it would rescan every earlier chunk.
  • A missing user starts at 0 in a Counter, so += works on the first chunk too.

Tip Try it: change seen, unique = set(), [] to seen, unique = [], [] and seen.add to seen.append. The output is the same, but each check now scans a list. On 100 chunks you will not notice; on a million you will.

Common mistakes

  • Using x in some_list inside a loop over a big collection. Each check is O(n); turn the list into a set once and check the set.
  • Writing items = items.sort(). .sort() works in place and returns None; use sorted(items) when you want a new list.
  • Reading a key with d["key"] when it might be missing, so a reply without that field crashes with KeyError. Use d.get("key", default).
  • Writing {} for an empty set. That is an empty dict; an empty set is set().
  • Thinking new = old or list(old) gives an independent copy of a list of dicts. The first is an alias, the second shares the inner dicts; use copy.deepcopy if you will edit them.
  • Calling list.pop(0) or insert(0, x) in a loop to process a queue. Each call is O(n); use collections.deque and popleft().

Practice

Write the code, then press Check. Your work is saved in this browser.

1Dedupe chunks, keep the order

Write dedupe(texts) that returns a new list without duplicates, keeping the first time each text appears, in the original order. It must stay fast for long lists, so do not use x in some_list.

Exercise
def dedupe(texts):
    # your code here
    return texts


print(dedupe(["a", "b", "a", "c", "b"]))
Hint

Either a set of seen texts plus a result list, or `list(dict.fromkeys(texts))`.

2Tokens per user

Each event is a tuple (user, tokens). Write tokens_per_user(events) that returns a dict mapping each user to their total tokens. Users with no events must not appear.

Exercise
def tokens_per_user(events):
    # your code here
    return {}


print(tokens_per_user([("asha", 120), ("ben", 40), ("asha", 30)]))
Hint

Loop with `for user, n in events:` and add into a `Counter()` or a `defaultdict(int)`, then return `dict(...)` of it.

3Top k chunks

Each chunk is a dict with "id" and "score". Write top_k(chunks, k) that returns the ids of the k highest-scoring chunks, highest first. When two scores tie, the smaller id (A to Z) comes first.

Exercise
def top_k(chunks, k):
    # your code here
    return [c["id"] for c in chunks[:k]]


print(top_k([{"id": "b", "score": 0.5}, {"id": "a", "score": 0.9}], 1))
Hint

Sort with `key=lambda c: (-c["score"], c["id"])`, then slice `[:k]`.

Interview questions

Q1What is the time complexity of common list operations in Python?

append and pop() at the end are amortised O(1). insert(0, x) and pop(0) are O(n) because every other item shifts. Indexing is O(1), and x in list is O(n) because it scans. For fast operations at both ends use collections.deque.

Q2Why is checking membership in a set faster than in a list?

A set is a hash table: Python hashes the value and jumps to where it would be, O(1) on average. A list has to compare against each item in turn, O(n). That is also why set items and dict keys must be hashable.

Q3What is the difference between a list and a tuple?

A list can change (add, remove, replace items); a tuple cannot after creation. Tuples are used for fixed records and multiple return values, and because they are immutable (when their items are too) they are hashable and can be dict keys or set items.

Q4Are Python dicts ordered?

Yes. Since Python 3.7 the language guarantees that dicts keep insertion order. Sets do not keep any order.

Q5What is the difference between a shallow and a deep copy?

A shallow copy (list(x), x.copy(), x[:]) creates a new outer container that holds the same inner objects. A deep copy (copy.deepcopy) recursively copies the inner objects too. Plain assignment copies nothing; it creates an alias.

Q6When would you use Counter, defaultdict or deque?

Counter to count things (tokens per user, word frequencies, most_common). defaultdict(list) to group items by a key without checking for missing keys. deque for a queue or a fixed-size window of recent items, since it has O(1) appends and pops at both ends.