Lists and tuples
Ordered collections — mutable lists and immutable tuples.
- Create, index, and modify lists
- Iterate over a collection with for
- Explain how a tuple differs from a list
A list is an ordered, changeable collection — the workhorse for "many of something." A tuple is its immutable cousin. Both connect directly to the data-structures fundamentals lesson: the shape you choose decides what's easy.
Lists: ordered and mutable
nums = [3, 1, 2]
nums[0] # 3 (index from 0)
nums.append(4) # [3, 1, 2, 4]
nums[0] = 9 # [9, 1, 2, 4] (lists can change in place)
len(nums) # 4
nums.sort() # [1, 2, 4, 9]Like strings, lists slice with [start:stop]. Unlike strings, they're
mutable — methods like append, sort, and remove change the list itself.
(Recall the reference-vs-value idea: two names for one list both see the change.)
Iterating
A for loop walks the items directly — no indexing needed:
for n in nums:
print(n)Need the index too? enumerate gives you both:
for i, n in enumerate(nums):
print(i, n)Tuples: ordered and immutable
A tuple is a fixed, unchangeable sequence, written with parentheses (or just commas):
point = (3, 4)
point[0] # 3
# point[0] = 9 # TypeError — tuples can't be changed
x, y = point # "unpacking": x = 3, y = 4Reach for a tuple when the collection shouldn't change — coordinates, a fixed pair, a function returning several values. The immutability is a feature: it signals "this won't be modified."
Where to go next
Lists hold values by position. Next: dictionaries and sets — holding values by key, and tracking uniqueness.