Skip to main content

03.1 - Lists & Tuples

Theory 25 min Beginner

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

MethodDescriptionExample
.append(x)Add to endlst.append(5)
.insert(i, x)Insert at index ilst.insert(0, "x")
.extend(iter)Add all itemslst.extend([4, 5])
.remove(x)Remove first occurrencelst.remove("banana")
.pop(i)Remove & return at indexlst.pop(-1)
.index(x)Find first occurrence indexlst.index("apple")
.count(x)Count occurrenceslst.count("a")
.sort()Sort in placelst.sort()
.reverse()Reverse in placelst.reverse()
.copy()Shallow copynew = lst.copy()
.clear()Remove all itemslst.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

ListTuple
MutabilityMutable (can change)Immutable (cannot change)
Syntax[1, 2, 3](1, 2, 3)
PerformanceSlightly slowerSlightly faster
Use as dict keyNo (unhashable)Yes (hashable)
Use caseCollection that changesFixed record, coordinates, DB row
MemoryMoreLess
# 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

TermDefinition
ListOrdered, mutable sequence: [1, 2, 3]
TupleOrdered, immutable sequence: (1, 2, 3)
MutableCan be changed after creation
ImmutableCannot be changed after creation
IndexingAccessing an element by position: lst[0]
SlicingExtracting a sub-sequence: lst[1:4]
Tuple unpackingAssigning tuple values to variables: x, y = (1, 2)
Shallow copyCopy of the container, but nested objects still shared
Deep copyFully 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 in membership tests
  • Assignment creates an alias — use .copy(), [:], or copy.deepcopy() to copy
  • Tuple unpacking a, b = tup is powerful — use it for swapping, function returns, loops
  • namedtuple adds named fields to tuples for readability