Lesson 67 min read

Lists & Tuples

Your go-to containers for storing collections of stuff

Lists — Ordered, Mutable Collections

A list is like a train with numbered cars — under the hood, Python lists work like dynamic arrays. Each car holds one item, you can add cars, remove cars, or swap what's inside any car. They're ordered (car 0 is always first), and you can put anything inside — numbers, strings, even other lists.

Lists are created with square brackets [] and items are separated by commas.

Creating & Accessing Lists

# Creating lists
colors = ["red", "blue", "green", "yellow"]
numbers = [10, 20, 30, 40, 50]
mixed = ["hello", 42, True, 3.14, None]
empty = []
# Indexing (same rules as strings!)
print(colors[0]) # First item
print(colors[-1]) # Last item
print(colors[1:3]) # Slice: items 1 and 2
# Length
print(len(colors))
# Check membership
print("blue" in colors)
print("purple" in colors)
Output
red
yellow
['blue', 'green']
4
True
False

Modifying Lists

Unlike strings, lists are mutable — you can change them after creation. You can add items, remove items, sort them, and more. Here are the essential list methods you'll use every day:

  • .append(x) — Add item to the end
  • .insert(i, x) — Insert item at index i
  • .pop(i) — Remove and return item at index i (defaults to last)
  • .remove(x) — Remove first occurrence of value x
  • .sort() — Sort in place
  • .reverse() — Reverse in place
  • .extend(list) — Add all items from another list

List Methods in Action

# Building a shopping list
cart = ["milk", "bread"]
cart.append("eggs") # Add to end
cart.insert(0, "butter") # Add at beginning
print("After adding:", cart)
cart.remove("bread") # Remove by value
last = cart.pop() # Remove & return last item
print(f"Removed: {last}")
print("After removing:", cart)
# Sorting
scores = [85, 42, 99, 71, 63]
scores.sort() # Sort ascending (in place)
print("Sorted:", scores)
scores.sort(reverse=True) # Sort descending
print("Top scores:", scores)
# Combine lists
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b) # Modifies a in place
print(a)
print([1, 2] + [3, 4]) # Creates new list with +
Output
After adding: ['butter', 'milk', 'bread', 'eggs']
Removed: eggs
After removing: ['butter', 'milk']
Sorted: [42, 63, 71, 85, 99]
Top scores: [99, 85, 71, 63, 42]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]

Tuples — The Immutable Cousin

A tuple is like a list that's been sealed in plastic wrap. Once created, you can't add, remove, or change items. Why would you want that? Because it's a promise: "This data won't change."

Tuples are created with parentheses () — or even without them, just commas. They're perfect for things like coordinates (x, y), RGB colors (255, 0, 128), or returning multiple values from a function.

Tuples & Unpacking

# Creating tuples
point = (3, 7)
rgb = (255, 128, 0)
singleton = (42,) # Need a trailing comma for 1 item!
print(point[0]) # Indexing works
print(len(rgb)) # Length works
# Unpacking — assign each element to a variable
x, y = point
print(f"x={x}, y={y}")
# Unpacking with * (star) to grab extras
first, *rest = [10, 20, 30, 40, 50]
print(f"First: {first}")
print(f"Rest: {rest}")
# Swapping is actually tuple unpacking!
a, b = 1, 2
a, b = b, a
print(f"a={a}, b={b}")
# Tuples as dictionary keys (lists can't do this!)
locations = {}
locations[(0, 0)] = "origin"
locations[(3, 4)] = "treasure"
print(locations)
Output
3
3
x=3, y=7
First: 10
Rest: [20, 30, 40, 50]
a=2, b=1
{(0, 0): 'origin', (3, 4): 'treasure'}
Note: Use a list when you need a collection that will change (shopping cart, to-do items). Use a tuple when the data should stay fixed (GPS coordinates, database records). Tuples are also slightly faster and use less memory.

Quick check

What does [1, 2, 3].pop(0) return?

Continue reading

Dynamic ArraysData Structure
Resizing strategy, amortized O(1) push
Static ArraysData Structure
A row of numbered boxes — fast to grab, fixed in size
ArraysJavascript
The Swiss Army knife of JavaScript collections
ArraysJava
Fixed-size boxes — declare, fill, and loop
LoopsDictionaries & Sets