Hints for lists, dicts, and maybe-None
🌍 In real life. A parcel label that only says box isn't much help. A good one says what's inside: box of 6 eggs, bag of letters for Dhaka. A courier can then handle it properly without opening it.
Collection hints work the same way: the square brackets say what's inside. Step by step:
list[int]: a list of ints, like[90, 75, 88]dict[str, int]: a dict with str keys and int values, like{"tea": 20}tuple[str, int]: a pair, a str then an int, like("Mina", 15)set[str]: a set of strs
The idea in one sentence: square brackets say what's inside a collection, list[int], dict[str, int], and str | None says "a string, or nothing".
Its words:
list[int]: a list of ints;dict[str, int]: str keys, int values;tuple[int, int]: exactly two intsX | None: maybe an X, maybeNoneOptional[X],List[int]: the older spellings of the same labels
def average(marks: list[int]) -> float:
return sum(marks) / len(marks)
prices: dict[str, int] = {"tea": 20, "samosa": 15}
student: tuple[str, int] = ("Mina", 15)
print(average([90, 75, 88]))
print(prices["tea"] + prices["samosa"], "rupees")
print(student[0], "is", student[1])Maybe a value, maybe nothing. Looking up a phone number might find one, or might not. Returning None for "not found" is common, and the hint says so with | (read it as or): -> str | None means "gives back a str, or None".
That label is a reminder for whoever calls the function: check for None before using the answer.
def find_phone(book: dict[str, str], name: str) -> str | None:
return book.get(name)
book = {"Mina": "01711-000111", "Rafi": "01812-000222"}
for who in ["Rafi", "Tara"]:
phone = find_phone(book, who)
if phone is None:
print(who, "isn't in the book")
else:
print(who, phone)
print(find_phone.__annotations__["return"])The older spelling. You'll see List[int], Dict[str, int] and Optional[str] in older code and tutorials. They come from the typing module and are the older way to write the same labels (Python doesn't treat List[int] as equal to list[int], so the tasks here expect the built-in spelling), and they need an import first (from typing import List). Without it, List is an unknown name: older Pythons stop with NameError: name 'List' is not defined as soon as the def line runs, and newer ones (like the Python in this app) stop as soon as anything reads the labels, such as __annotations__. In new code, use the built-in list[int] and str | None.
And remember, these are still only labels. Python won't stop the wrong thing going in:
prices: dict[str, int] = {"tea": 20}
prices["cake"] = "fifty"
print(prices)Why say what's inside? list alone tells a reader nothing about the items; list[str] tells them they can call .upper() on each one. And -> str | None is a reminder that the caller must check for None before using the result.
Mistakes and edge cases.
- Forgetting the None check. A function hinted
-> str | Nonereally can returnNone;result.upper()then gives an AttributeError. - Checking against a hint.
isinstance([1], list[int])givesTypeError: isinstance() argument 2 cannot be a parameterized generic. Checkisinstance(x, list)instead. - Mixing spellings.
List[int]andlist[int]mean the same to people, but the tasks here expect the built-inlist[int].
Quiz
Which hint means "a list of whole numbers"?
- list[int]
- int[list]
- list(int)
What does this print?
def first(names: list[str]) -> str | None: if names: return names[0] return None print(first([])) print(first(["Mina", "Rafi"]))What does
dict[str, int]describe?- A dict whose keys are strs and values are ints
- A dict whose keys are ints and values are strs
- A dict with exactly two items
What does this print?
marks: list[int] = [80, 90] marks.append("absent") print(len(marks))Which line has a mistake?
def find_phone(book: dict[str, str], name: str) -> str | None: return book[name] book = {"Mina": "017"} print(find_phone(book, "Tara"))
Coding tasks
Write
average(marks: list[int]) -> float: the average of the marks, or0.0when the list is empty.Fix
find_phoneso a missing name gives backNoneinstead of an error, and give it the hintsbook: dict[str, str],name: strand-> str | None.Write
count_words(text: str) -> dict[str, int]: how many times each word (split on spaces) appears, in the order the words first appear.