Skip to content
Aabha AI Academy
Skip to reading

Python · Module 3

Collections and records

Outcome: choose a container and avoid unintended shared edits. Prerequisite: Module 2. Profile: Python basics. Time: about 2 hours.

Four useful shapes

A list stores a sequence: [20, 30, 15]. It keeps order, allows repeats and can change. A tuple also stores a sequence, often for a small fixed grouping such as (x, y); its own entries cannot be reassigned. A dictionary maps unique keys to values: {"topic": "python", "minutes": 25}. A set stores unique elements and is useful for membership or deduplication when order is not the purpose.

Choose from the question you need to answer. “What was the third session?” suggests an ordered sequence. “How many minutes are in this record?” suggests a named dictionary field. “Which topics occurred at least once?” suggests a set. No container is best for every problem.

Positions and keys are different

Python sequence indexing begins at zero: scores[0] is the first item, and scores[-1] is the last. An out-of-range position raises IndexError. Slicing selects a range: scores[:2] gets the first two items because the stop position is excluded. A slice beyond the end is tolerated, whereas an individual invalid index is not.

Dictionary lookup uses a key, not a position. record["minutes"] raises KeyError if the required key is absent. record.get("notes", "not supplied") gives a fallback for an optional field. Do not use a default of zero for a required measurement simply to hide missing data; that changes the meaning of the record.

Lists can contain dictionaries. This is a natural way to represent small tables before we introduce pandas. Each row is a record and each dictionary key names a field. A row's position and its identifier are separate concepts: sorting records changes positions but should not change identifiers.

Worked example

# Profile: Python basics
scores = [2, 4, 3]
copy_of_scores = scores.copy()
copy_of_scores.append(5)
print("Original:", scores)
print("Copy:", copy_of_scores)
print("First two:", scores[:2])
record = {"topic": "python", "minutes": 25}
print("Topic:", record["topic"])
print("Notes:", record.get("notes", "not supplied"))
counts = {}
for topic in ["python", "data", "python", "charts"]:
    counts[topic] = counts.get(topic, 0) + 1
print("Counts:", counts)
print("Unique topics:", sorted(set(["python", "data", "python"])))
point = (3, 5)
x, y = point
print("Point:", x, y)

Download this worked script

The original list remains [2, 4, 3]; the copy becomes [2, 4, 3, 5]. Counts are python: 2, data: 1, charts: 1. The sorted unique topic list is ['data', 'python']. Set iteration is not the right way to promise a display order, so we explicitly sort it.

The tuple assignment x, y = point is unpacking: two values are assigned to two names in order. If their counts differ, Python raises ValueError. Unpacking can clarify code, but only when the structure is known.

Names can share an object

edited = original does not make a new list. Both names refer to the same list; edited.append(40) is therefore visible through original. For a list of numbers, original.copy() creates a new outer list whose independent additions do not affect the original.

Two names can point to one list; copying creates a separate outer listOpen the diagram at full size

Read the diagram explanation

On the left, two names refer to one list. On the right, copying a flat list creates an independent outer list.

This is a shallow copy. If a list contains other mutable lists or dictionaries, those inner objects can still be shared. For this module, copy flat lists of immutable numbers or strings. Later code uses explicit copies at boundaries rather than assuming that assignment isolates data.

The counting pattern is worth tracing: counts.get(topic, 0) supplies zero when the key is first encountered; adding one creates the first count. Later occurrences read the existing count and increase it. A dictionary preserves insertion order, but that is not the same as alphabetic or numeric sorting.

Practice

  • 3A: count ['python', 'data', 'python', 'charts', 'data'] with a dictionary and loop. Explain the first and second updates for python.
  • 3B: start with [20, 30], create an independent outer list, append 40 and show both lists. First predict what would go wrong with plain assignment.
  • 3C: return a sorted list of unique topics. Explain why a set is appropriate here but would lose information if you needed the original number of sessions.

Use exercises/03_collections.py for the checks. Try empty collections and a topic appearing once.

Choose, retrieve and explain

Before choosing code, choose the container and say why: an ordered history that may repeat a topic; one session with named topic/minutes fields; unique topic names; and a fixed pair of screen coordinates. More than one representation can work, but explain order, repetition, named lookup and intended mutability.

Now use sessions = [{"topic": "python", "minutes": 20}, {"topic": "data", "minutes": 30}, {"topic": "charts", "minutes": 10}]. Retrieve the second session's minutes, slice the first two sessions, and unpack (4, 7) into x and y. Predict the types as well as the values. Check your explanations in the separate answer guide.

For the nested-copy exit question, trace this small counterexample:

original = [{"minutes": 20}]
copied = original.copy()
copied[0]["minutes"] = 99
print(original[0]["minutes"])  # 99: the inner dictionary is shared
pair = ([1, 2], "label")
pair[0].append(3)
print(pair[0])  # [1, 2, 3]: tuple entries are fixed, but this entry is a list

The outer collection's mutability and an inner object's mutability are separate questions. Independent nested copies are beyond the required flat-list exercises; this trace explains the limitation rather than asking you to guess it.

Exit check

Why is record["minutes"] different from scores[0]? When would using .get(..., 0) be misleading? Does a tuple guarantee every object inside it is immutable? Why can a shallow copy still share an inner dictionary?

Further reading

Read the separate answers and explanations

Reading progress

11 lessons remain open to guests. Marking a lesson read records reading only; it does not award assessment credit or a certificate.

Device reading marks require browser storage. Reading is always available.

Sign in or create an account to save separate account progress. Your current page is kept.