Python 3D Academyবাংলা

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:

  1. list[int]: a list of ints, like [90, 75, 88]
  2. dict[str, int]: a dict with str keys and int values, like {"tea": 20}
  3. tuple[str, int]: a pair, a str then an int, like ("Mina", 15)
  4. 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 ints
  • X | None: maybe an X, maybe None
  • Optional[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])
dict[str, int] reads as "keys are strs, values are ints": the key type comes first.

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)
"fifty" is a str in a dict labelled for int values. It goes in quietly; a type checker would flag that line.

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 | None really can return None; result.upper() then gives an AttributeError.
  • Checking against a hint. isinstance([1], list[int]) gives TypeError: isinstance() argument 2 cannot be a parameterized generic. Check isinstance(x, list) instead.
  • Mixing spellings. List[int] and list[int] mean the same to people, but the tasks here expect the built-in list[int].

Quiz

  1. Which hint means "a list of whole numbers"?

    • list[int]
    • int[list]
    • list(int)
  2. What does this print?

    def first(names: list[str]) -> str | None:
        if names:
            return names[0]
        return None
    
    print(first([]))
    print(first(["Mina", "Rafi"]))
  3. 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
  4. What does this print?

    marks: list[int] = [80, 90]
    marks.append("absent")
    print(len(marks))
  5. 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

  1. Write average(marks: list[int]) -> float: the average of the marks, or 0.0 when the list is empty.

  2. Fix find_phone so a missing name gives back None instead of an error, and give it the hints book: dict[str, str], name: str and -> str | None.

  3. Write count_words(text: str) -> dict[str, int]: how many times each word (split on spaces) appears, in the order the words first appear.