Skip to lesson content

PYTHON / LESSON 8 OF 18

Collections

Read the explanations, work through the examples, and complete the student tasks.

Learning goals

Choose between lists, tuples, sets, and dictionaries and use their methods appropriately.

Explanation

A list is an ordered mutable sequence with duplicates allowed. A tuple is an ordered immutable sequence; objects inside a tuple can still be mutable. A set stores unique hashable items and does not provide positional indexing. A dictionary maps unique hashable keys to values and preserves insertion order.

Choose a list for changing ordered work, a tuple for a fixed grouping, a set for membership and uniqueness, and a dictionary for lookup by key. Hashable is more precise than simply immutable: a tuple containing a list cannot be a dictionary key.

Example 1 A list and a tuple

scores = [70, 80, 80]
scores.append(90)
scores.extend([60, 100])
scores.insert(0, 50)
scores.remove(80)
last_score = scores.pop()
print(scores)
print(last_score, scores.count(80), scores.index(90))
point = (10, 20)
x, y = point
print(x, y)

Expected output:

[50, 70, 80, 90, 60]
100 1 3
10 20

append adds one object; extend adds items from an iterable. remove deletes the first equal value. pop removes and returns an item. Tuple unpacking gives descriptive names to its elements.

Example 2 Sets and dictionaries

skills = {"Python", "SQL", "Python"}
skills.add("Testing")
skills.update(["SQL", "Git"])
print(sorted(skills))
print(sorted(skills & {"Python", "Java"}))
student = {"name": "Ali", "score": 85}
student["score"] = 90
student.update({"city": "Karachi"})
print(student.get("email", "Not supplied"))
for key, value in student.items():
    print(key, value)

Expected output begins ['Git', 'Python', 'SQL', 'Testing'], then ['Python'], then Not supplied. The remaining lines show name Ali, score 90, and city Karachi. sorted makes set output predictable; it does not mean the set itself has a sorted order.

Dictionary keys(), values(), and items() expose its keys, values, and pairs. Set union uses |; difference uses -. clear empties mutable collections. The source's compact method chart is simplified: dictionaries and sets also support pop, but with different arguments and semantics from a list.

Student tasks

1. Maintain a shopping list: append one item, insert one at the beginning, and remove one by value.

2. Find the unique values in [2, 2, 3, 1, 3] and print them sorted. Expected: [1, 2, 3].

3. Store three products and their prices in a dictionary. Use get to handle a missing product.

4. Given sets {1, 2, 3} and {3, 4}, show their union, intersection, and first-set difference.

Completion check: explain why you chose each collection and avoid indexing a set.