Lesson 3 of 5 · Control Flow · 3 min read · Updated
Lists and dictionaries
The two collections you will use for almost everything.
A list holds items in order. A dictionary holds pairs, looked up by name rather than position. Between them they cover most of what a program needs to remember.
marks = [72, 85, 63, 91]
print(marks[0]) # 72 — counting starts at zero
print(marks[-1]) # 91 — negative counts from the end
print(len(marks)) # 4
print(sum(marks)) # 311
print(max(marks)) # 91
marks.append(78) # add to the end
marks.sort() # smallest first
print(marks[1:3]) # [72, 78] — a slice
Note
marks[-1] is the last item, marks[-2] the one before it. C has nothing like this — reading past the end there is a bug, while in Python a negative index is a feature.
Dictionaries: looking up by name
student = {
"name": "Priya",
"roll": 42,
"marks": 87.5
}
print(student["name"]) # Priya
print(student.get("email", "—")) # — when the key is missing
student["marks"] = 90 # change it
student["email"] = "p@x.com" # add a new pair
for key, value in student.items():
print(key, "=", value)
Warning
student["email"] raises a KeyError when the key is missing, which stops the program. student.get("email") returns None instead, and takes a default. Use get whenever the key might not be there.
Putting them together
students = [
{"name": "Priya", "marks": 87},
{"name": "Arun", "marks": 73},
{"name": "Meena", "marks": 91}
]
for s in students:
print(s["name"], s["marks"])
# The highest mark, in one line:
best = max(students, key=lambda s: s["marks"])
print("Top:", best["name"])
What does student.get("email", "—") return when there is no email key?
Try this now
- Build a list of student dictionaries and print the average mark.
- Count how many times each word appears in a sentence, using a dictionary.
- Print only the students who scored above the average.
Create a free account to save your progress, or sign in.