Lists and Tuples
Python's two core sequence types -- mutable lists and immutable tuples -- and when to use each.
2 min read
Lists and tuples both hold an ordered collection of items, and both support indexing and slicing the same way. The difference that matters is mutability: a list can change after it's created; a tuple can't.
Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry -- negative indices count from the endLists are mutable — you can add, remove, and change items in place:
fruits.append("date") # add to the end
fruits.insert(1, "apricot") # insert at a specific position
fruits.remove("banana") # remove by value
fruits[0] = "avocado" # replace by index
print(len(fruits)) # current number of itemsSlicing
Slicing pulls out a sub-sequence with start:stop (stop is exclusive):
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2] -- from the start
print(numbers[3:]) # [3, 4, 5] -- to the end
print(numbers[::2]) # [0, 2, 4] -- every second item
print(numbers[::-1]) # [5, 4, 3, 2, 1, 0] -- reversedSlicing always returns a new list, leaving the original untouched — a common way to make a copy is numbers[:].
Tuples
point = (3, 4)
print(point[0]) # 3Tuples look and behave like lists for reading, but trying to change one fails immediately:
point[0] = 5
# TypeError: 'tuple' object does not support item assignmentThat immutability is the whole point. Use a tuple when a value is meant to be fixed once created — coordinates, an RGB color, a database row — signaling to anyone reading the code (and to Python itself) that it shouldn't change. A single-item tuple needs a trailing comma to be recognized as one: (5,), not (5) (which is just the number 5 in parentheses).
Unpacking
Both lists and tuples support unpacking directly into named variables:
point = (3, 4)
x, y = point
print(x, y) # 3 4
first, *rest = [1, 2, 3, 4]
print(first) # 1
print(rest) # [2, 3, 4]The *rest syntax collects "everything else" into a list — handy for peeling off the first item (or first few) without manual slicing.
Which one to use
Default to a list for any collection you expect to grow, shrink, or reorder. Reach for a tuple when the collection's size and contents are fixed by design — function return values with multiple parts, coordinate pairs, or anything used as a dictionary key (which must be immutable, and so can't be a list — but can be a tuple).
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.