Lists, Tuples, and Dictionaries
Lists, Tuples, and Dictionaries
Why Collections Matter
Single variables are great, but real programs juggle many related values: a list of scores, a set of coordinates, a phone book of names and numbers. Python provides built-in collection types to store and organize that data. The three you will use constantly are lists, tuples, and dictionaries.
Lists Are Ordered and Mutable
A list is an ordered collection written with square brackets. Items can be added, removed, or changed after creation, which makes lists mutable. Indexing starts at zero, so the first item is at position 0.
scores = [88, 92, 75, 100]
scores.append(84) # add to the end
scores[0] = 90 # change the first element
print(scores[0]) # 90
print(len(scores)) # 5
for s in scores:
print(s)
Common list methods include .append(), .remove(), .sort(), and .pop(). Slicing with scores[1:3] returns a sub-list from index 1 up to (but not including) index 3.
Tuples Are Ordered and Immutable
A tuple is written with parentheses and behaves like a list you cannot change. Once created, you cannot add, remove, or reassign elements. That makes tuples ideal for fixed data such as coordinates or configuration values, and Python processes them slightly faster.
point = (3, 7)
x, y = point # tuple unpacking
print(x, y) # 3 7
Unpacking lets you assign several variables in one line, which is cleaner than reading individual indexes.
Dictionaries Map Keys to Values
A dictionary stores pairs of keys and values, written with curly braces. You look things up by key instead of by position, which makes dictionaries perfect for records such as a user profile.
student = {"name": "Ada", "grade": 9, "subjects": ["Math", "CS"]}
print(student["name"]) # Ada
student["grade"] = 10
student["city"] = "London" # add a new key
for key in student:
print(key, student[key])
Use .get() with a fallback value to avoid errors when a key might be missing: student.get("age", 0) returns 0 if age is absent.
Key Points
- Lists are mutable, ordered, and written with square brackets.
- Tuples are immutable, ordered, and written with parentheses.
- Dictionaries map keys to values and look up items by key.
- Indexing starts at zero; slicing uses [start:stop].
- Use .get() on dictionaries to supply a default when a key is missing.