03.1 - Lists & Tuples
Lists — The Most Used Data Structure
A list is an ordered, mutable sequence of items. Lists can hold any type, including mixed types.
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None]
empty = []
nested = [[1, 2], [3, 4], [5, 6]]
# From other iterables
from_string = list("hello") # ['h', 'e', 'l', 'l', 'o']
from_range = list(range(5)) # [0, 1, 2, 3, 4]
Indexing and Slicing
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# 0 1 2 3 4
# -5 -4 -3 -2 -1
# Single element
fruits[0] # "apple"
fruits[-1] # "elderberry" (last)
fruits[-2] # "date"
# Slicing [start:stop:step]
fruits[1:3] # ["banana", "cherry"] stop is exclusive
fruits[:3] # ["apple", "banana", "cherry"]
fruits[2:] # ["cherry", "date", "elderberry"]
fruits[::2] # ["apple", "cherry", "elderberry"] (every 2nd)
fruits[::-1] # reversed list
List Methods
| Method | Description | Example |
|---|---|---|
.append(x) | Add to end | lst.append(5) |
.insert(i, x) | Insert at index i | lst.insert(0, "x") |
.extend(iter) | Add all items | lst.extend([4, 5]) |
.remove(x) | Remove first occurrence | lst.remove("banana") |
.pop(i) | Remove & return at index | lst.pop(-1) |
.index(x) | Find first occurrence index | lst.index("apple") |
.count(x) | Count occurrences | lst.count("a") |
.sort() | Sort in place | lst.sort() |
.reverse() | Reverse in place | lst.reverse() |
.copy() | Shallow copy | new = lst.copy() |
.clear() | Remove all items | lst.clear() |
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Modifying
numbers.append(7) # [3,1,4,1,5,9,2,6,7]
numbers.insert(0, 0) # [0,3,1,4,1,5,9,2,6,7]
numbers.remove(1) # removes first 1
# Sorting
numbers.sort() # in-place ascending
sorted_copy = sorted(numbers) # new sorted list
sorted_desc = sorted(numbers, reverse=True)
# Key-based sort
words = ["banana", "apple", "cherry", "date"]
words.sort(key=len) # sort by string length
words.sort(key=str.lower) # case-insensitive sort
List Arithmetic
a = [1, 2, 3]
b = [4, 5, 6]
a + b # [1, 2, 3, 4, 5, 6] concatenation
a * 3 # [1, 2, 3, 1, 2, 3, 1, 2, 3]
# Check membership
3 in a # True
7 not in a # True
# Length
len(a) # 3
# Aggregate
min(a) # 1
max(a) # 3
sum(a) # 6
Mutability and Copying
Lists are mutable and use reference semantics — assignment creates an alias, not a copy!
a = [1, 2, 3]
b = a # b is an alias — SAME list!
b.append(4)
print(a) # [1, 2, 3, 4] — modified!
# To create a copy
b = a.copy() # shallow copy
b = a[:] # slice copy (same as copy())
b = list(a) # constructor copy
import copy
b = copy.deepcopy(a) # deep copy (for nested lists)
Tuples — Immutable Sequences
A tuple is like a list but immutable — cannot be changed after creation.
# Creating tuples
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # trailing comma required for single-element tuple
empty = ()
# Parentheses are optional (packing)
coordinates = 10, 20 # tuple packing
x, y = coordinates # tuple unpacking
# From iterable
t = tuple([1, 2, 3])
Tuple Unpacking
One of Python's most powerful features:
# Basic unpacking
x, y, z = (1, 2, 3)
a, b = b, a # swap values!
# Extended unpacking (*)
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
head, *middle, last = [1, 2, 3, 4, 5]
# head=1, middle=[2,3,4], last=5
# In loops
points = [(1, 2), (3, 4), (5, 6)]
for x, y in points:
print(f"x={x}, y={y}")
# Function returns
def min_max(lst):
return min(lst), max(lst) # returns a tuple
lo, hi = min_max([3, 1, 4, 1, 5, 9])
# lo=1, hi=9
List vs Tuple — When to Use
| List | Tuple | |
|---|---|---|
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slightly slower | Slightly faster |
| Use as dict key | No (unhashable) | Yes (hashable) |
| Use case | Collection that changes | Fixed record, coordinates, DB row |
| Memory | More | Less |
# Use tuple for fixed records
person = ("Alice", 30, "Montreal") # name, age, city
db_row = (1, "admin", True)
# Use list for collections that change
cart = ["apple", "bread"]
cart.append("milk")
Named Tuples
namedtuple gives tuple fields names — best of both worlds:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x # 3 (readable!)
p.y # 4
p[0] # 3 (still works like a tuple)
Person = namedtuple("Person", ["name", "age", "city"])
alice = Person("Alice", 30, "Montreal")
print(f"{alice.name} is {alice.age} years old")
Key Vocabulary
| Term | Definition |
|---|---|
| List | Ordered, mutable sequence: [1, 2, 3] |
| Tuple | Ordered, immutable sequence: (1, 2, 3) |
| Mutable | Can be changed after creation |
| Immutable | Cannot be changed after creation |
| Indexing | Accessing an element by position: lst[0] |
| Slicing | Extracting a sub-sequence: lst[1:4] |
| Tuple unpacking | Assigning tuple values to variables: x, y = (1, 2) |
| Shallow copy | Copy of the container, but nested objects still shared |
| Deep copy | Fully independent copy including nested objects |
Summary
- Lists
[...]are mutable ordered sequences — use for collections that change - Tuples
(...)are immutable — use for fixed records, coordinates, dict keys - Both support indexing, slicing, and
inmembership tests - Assignment creates an alias — use
.copy(),[:], orcopy.deepcopy()to copy - Tuple unpacking
a, b = tupis powerful — use it for swapping, function returns, loops namedtupleadds named fields to tuples for readability
📄️ 03.1 - Lists & Tuples
Master Python's ordered sequences: lists (mutable) and tuples (immutable) — creation, indexing, slicing, methods, and use cases
📄️ 03.2 - Dicts & Sets
Master Python's key-value store (dict) and unique collection (set) — creation, operations, and real-world patterns
📄️ 03.3 - Advanced Collections
Leverage Python's collections module for performance-optimized data structures beyond the built-ins
📄️ Lab - Module 03
Build a student grade book using lists, dictionaries, sets, and the collections module
📄️ Quiz - Module 03
30 questions on lists, tuples, dicts, sets, and the collections module