Chapter 6: Collections
Explore Python’s built-in collections: lists, tuples, sets, dicts, plus iteration and comprehensions.
Downloadchapter6.py
Objectives
- Create and manipulate
list
objects: indexing, slicing, methods. - Define
tuple
for immutable sequences; unpacking. - Work with
set
: uniqueness, union, intersection, difference. - Manage
dict
: key–value access, methods, iteration. - Iterate through collections with
for
,enumerate
,zip
. - Build list and dict comprehensions for concise expressions.
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:
Method | Description | Example |
---|---|---|
append(x) | Add x at end | fruits.append("date") |
insert(i, x) | Insert x at index i | fruits.insert(1,"fig") |
remove(x) | Remove first x | fruits.remove("banana") |
pop([i]) | Remove & return item at i | fruits.pop(2) |
sort() | Sort in place | fruits.sort() |
reverse() | Reverse in place | fruits.reverse() |
extend(iter) | Append items from iterable | fruits.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:
union
:a | b
intersection
:a & b
difference
:a - b
symmetric_difference
:a ^ b
4. Dictionaries
Key–value mappings:
# Creation
person = {"name": "Alice", "age": 30}
empty = {}
# Access & modify
name = person["name"]
person["city"] = "Rome"
Useful methods:
keys()
,values()
,items()
get(key, default)
,pop(key)
update(other_dict)
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
- Create a list of numbers 1–20, slice out the even-indexed ones.
- Use a tuple to store a sequence of coordinates and unpack them.
- Given two sets, compute their union, intersection, and difference.
- Build a dictionary from two lists: keys and values.
- Write a list comprehension to filter and transform a list of strings.