Chapter 6: Collections

Explore Python’s built-in collections: lists, tuples, sets, dicts, plus iteration and comprehensions.

Download chapter6.py

Objectives

1. Lists

Mutable, ordered sequences:

# Creation
fruits = ["apple", "banana", "cherry"]
empty = []

# Indexing & slicing
first = fruits[0]          # "apple"
subset = fruits[1:3]       # ["banana", "cherry"]

Common methods:

MethodDescriptionExample
append(x)Add x at endfruits.append("date")
insert(i, x)Insert x at index ifruits.insert(1,"fig")
remove(x)Remove first xfruits.remove("banana")
pop([i])Remove & return item at ifruits.pop(2)
sort()Sort in placefruits.sort()
reverse()Reverse in placefruits.reverse()
extend(iter)Append items from iterablefruits.extend(["kiwi"])

2. Tuples

Immutable, ordered sequences:

# Creation
coords = (10, 20)
single = (42,)        # trailing comma

# Unpacking
x, y = coords         # x=10, y=20

Tuples support indexing, slicing but not modification.

3. Sets

Unordered collections of unique elements:

# Creation
s = {1, 2, 3}
empty_set = set()

# Add/remove
s.add(4)
s.remove(2)

Set operations:

4. Dictionaries

Key–value mappings:

# Creation
person = {"name": "Alice", "age": 30}
empty = {}

# Access & modify
name = person["name"]
person["city"] = "Rome"

Useful methods:

5. Iteration & Comprehensions

a) Iteration

for item in fruits:
    print(item)

for i, v in enumerate(fruits, 1):
    print(i, v)

for k, v in person.items():
    print(k, v)

b) List Comprehensions

# squares of even numbers 0–9
squares = [x*x for x in range(10) if x % 2 == 0]

# nested comprehension
pairs = [(i, j) for i in [1,2] for j in ['a','b']]

c) Dict Comprehensions

# map number to its square
sq_map = {x: x*x for x in range(5)}

Exercises

  1. Create a list of numbers 1–20, slice out the even-indexed ones.
  2. Use a tuple to store a sequence of coordinates and unpack them.
  3. Given two sets, compute their union, intersection, and difference.
  4. Build a dictionary from two lists: keys and values.
  5. Write a list comprehension to filter and transform a list of strings.