Module 3 - Collections - Lists, Tuples, Sets & Dictionaries
This module covers Python's built-in collection types: lists, tuples, sets, and dictionaries. These are fundamental data structures you'll use in every Python program.
1. Lists
Lists are ordered, mutable collections that can contain mixed data types.
1.1 Creating Lists
# Empty list
empty = []
empty = list()
# List with elements
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]
# List from other iterables
from_string = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
from_range = list(range(5)) # [0, 1, 2, 3, 4]
1.2 Accessing Elements
fruits = ["apple", "banana", "orange", "mango"]
# Indexing
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'mango' (last element)
# Slicing
print(fruits[1:3]) # ['banana', 'orange']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['orange', 'mango']
print(fruits[::2]) # ['apple', 'orange'] (every 2nd element)
print(fruits[::-1]) # Reverse list
1.3 Modifying Lists
numbers = [1, 2, 3, 4, 5]
# Changing elements
numbers[0] = 10
numbers[1:3] = [20, 30]
# Adding elements
numbers.append(6) # Add to end
numbers.insert(0, 0) # Insert at index
numbers.extend([7, 8, 9]) # Add multiple elements
# Removing elements
numbers.remove(10) # Remove first occurrence
popped = numbers.pop() # Remove and return last
popped = numbers.pop(0) # Remove at index
del numbers[0] # Delete by index
numbers.clear() # Remove all elements
1.4 List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Sorting
numbers.sort() # In-place sort
sorted_nums = sorted(numbers) # Returns new sorted list
numbers.sort(reverse=True) # Descending order
# Reversing
numbers.reverse() # In-place reverse
reversed_nums = numbers[::-1] # Returns new reversed list
# Searching
print(numbers.index(5)) # Index of first occurrence
print(numbers.count(1)) # Count occurrences
# Other operations
print(len(numbers)) # Length
print(max(numbers)) # Maximum value
print(min(numbers)) # Minimum value
print(sum(numbers)) # Sum of elements
1.5 List Comprehensions
# Basic list comprehension
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Multiple conditions
filtered = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
# With transformation
upper_words = [word.upper() for word in ["hello", "world"]]
# Nested comprehension
matrix = [[i+j for j in range(3)] for i in range(3)]
2. Tuples
Tuples are ordered, immutable collections.
2.1 Creating Tuples
# Empty tuple
empty = ()
empty = tuple()
# Tuple with elements
numbers = (1, 2, 3, 4, 5)
single = (42,) # Single element (comma required)
mixed = (1, "Hello", 3.14, True)
# Without parentheses
point = 10, 20
print(type(point)) # <class 'tuple'>
2.2 Tuple Operations
coordinates = (10, 20, 30)
# Indexing and slicing (like lists)
print(coordinates[0]) # 10
print(coordinates[1:]) # (20, 30)
# Immutability
# coordinates[0] = 15 # TypeError!
# Concatenation
t1 = (1, 2, 3)
t2 = (4, 5, 6)
combined = t1 + t2
# Repetition
repeated = t1 * 3 # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Unpacking
x, y, z = coordinates
2.3 When to Use Tuples vs Lists
# Use tuples for:
coordinates = (10, 20) # Fixed data
rgb_color = (255, 128, 0) # Immutable records
database_record = ("John", 25, "NYC")
# Use lists for:
shopping_cart = ["apple", "banana"] # Mutable collections
tasks = ["task1", "task2", "task3"] # Dynamic data
3. Sets
Sets are unordered collections of unique elements.
3.1 Creating Sets
# Empty set (must use set(), not {})
empty = set()
# Set with elements
numbers = {1, 2, 3, 4, 5}
mixed = {1, "hello", 3.14, True}
# From iterable
from_list = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}
from_string = set("hello") # {'h', 'e', 'l', 'o'}
3.2 Set Operations
# Adding elements
numbers = {1, 2, 3}
numbers.add(4)
numbers.update([5, 6, 7])
# Removing elements
numbers.remove(3) # Raises error if not found
numbers.discard(3) # No error if not found
popped = numbers.pop() # Remove and return arbitrary element
numbers.clear() # Remove all elements
# Membership testing (fast)
print(3 in numbers)
print(10 not in numbers)
3.3 Set Mathematics
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# Union (all elements)
print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b))
# Intersection (common elements)
print(a & b) # {4, 5}
print(a.intersection(b))
# Difference (in a but not in b)
print(a - b) # {1, 2, 3}
print(a.difference(b))
# Symmetric difference (in either but not both)
print(a ^ b) # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b))
# Subset and superset
print({1, 2}.issubset(a)) # True
print(a.issuperset({1, 2})) # True
3.4 Frozenset (Immutable Set)
# Immutable set
fs = frozenset([1, 2, 3, 4, 5])
# Can be used as dictionary key
d = {fs: "value"}
# Cannot be modified
# fs.add(6) # AttributeError!
4. Dictionaries
Dictionaries store key-value pairs and are unordered (ordered from Python 3.7+).
4.1 Creating Dictionaries
# Empty dictionary
empty = {}
empty = dict()
# Dictionary literal
person = {
"name": "John",
"age": 25,
"city": "NYC"
}
# From key-value pairs
items = dict([("name", "John"), ("age", 25)])
# Using dict comprehension
squares = {x: x**2 for x in range(6)}
4.2 Accessing Values
person = {"name": "John", "age": 25, "city": "NYC"}
# Direct access
print(person["name"]) # 'John'
# print(person["phone"]) # KeyError!
# Safe access with get()
print(person.get("name")) # 'John'
print(person.get("phone")) # None
print(person.get("phone", "N/A")) # 'N/A' (default)
4.3 Modifying Dictionaries
person = {"name": "John", "age": 25}
# Adding/updating
person["city"] = "NYC" # Add new key
person["age"] = 26 # Update existing
# Update multiple
person.update({"country": "USA", "zip": "10001"})
# Removing
del person["city"] # Delete key
age = person.pop("age") # Remove and return value
person.popitem() # Remove and return last item
person.clear() # Remove all items
4.4 Dictionary Methods
person = {"name": "John", "age": 25, "city": "NYC"}
# Get all keys, values, items
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['John', 25, 'NYC'])
print(person.items()) # dict_items([('name', 'John'), ...])
# Checking membership
print("name" in person) # True (checks keys)
print("John" in person.values()) # True
# Default values
person.setdefault("country", "USA") # Add if not exists
# Copy
person_copy = person.copy()
4.5 Iterating Dictionaries
person = {"name": "John", "age": 25, "city": "NYC"}
# Iterate keys
for key in person:
print(key, person[key])
# Iterate key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Iterate values only
for value in person.values():
print(value)
4.6 Dictionary Comprehensions
# Basic comprehension
squares = {x: x**2 for x in range(6)}
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# Transform existing dict
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
grades = {name: "Pass" if score >= 80 else "Fail"
for name, score in scores.items()}
5. Nested Collections
# List of dictionaries
students = [
{"name": "John", "age": 20},
{"name": "Jane", "age": 22},
{"name": "Bob", "age": 21}
]
# Dictionary of lists
courses = {
"Math": ["John", "Jane"],
"Physics": ["Jane", "Bob"],
"Chemistry": ["John", "Bob"]
}
# Accessing nested data
print(students[0]["name"]) # 'John'
print(courses["Math"][0]) # 'John'
6. Collection Operations Summary
| Operation | List | Tuple | Set | Dict |
|---|---|---|---|---|
| Ordered | ✅ | ✅ | ❌ | ✅* |
| Mutable | ✅ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | Keys: ❌ |
| Indexing | ✅ | ✅ | ❌ | Keys |
| Use case | Sequences | Fixed data | Unique items | Key-value |
*From Python 3.7+
7. Choosing the Right Collection
# Use LIST when:
shopping_cart = ["apple", "banana", "orange"] # Order matters
tasks = ["task1", "task2"] # Mutable sequence needed
# Use TUPLE when:
coordinates = (10, 20) # Immutable data
rgb = (255, 128, 0) # Fixed structure
# Use SET when:
unique_tags = {"python", "coding", "tutorial"} # Uniqueness required
visited_pages = {"/home", "/about", "/contact"} # Fast membership test
# Use DICT when:
user = {"name": "John", "email": "john@example.com"} # Key-value mapping
config = {"host": "localhost", "port": 8000} # Configuration
Summary
✅ Lists: ordered, mutable, allow duplicates
✅ Tuples: ordered, immutable, allow duplicates
✅ Sets: unordered, mutable, unique elements
✅ Dictionaries: key-value pairs, keys must be unique
✅ List/dict comprehensions for concise code
✅ Choose the right collection for your use case
Next Steps
In Module 4, you'll learn:
- Control flow (if, elif, else)
- Loops (for, while)
- Break, continue, pass
- Loop patterns
Practice Exercises
- Create a list of 10 random numbers and find min, max, and average
- Write a program to remove duplicates from a list using sets
- Create a dictionary to store student names and grades, then calculate class average
- Build a phone book using nested dictionaries
- Use list comprehension to create a list of prime numbers from 1-100
Create a program that:
- Takes a paragraph as input
- Counts word frequency using a dictionary
- Displays the top 5 most common words
- Stores unique words in a set