CodeBlanks Logo Icon CodeBlanks

typing.List and Dict

Learn generic types with typing.List and Dict.

typing.List and Dict

To declare the inner type of a list, use typing.List: List[int] means a list of integers. For dicts use Dict: Dict[str, int] means a dict with string keys and integer values.

from typing import List, Dict

def total(nums: List[int]) -> int:
    return sum(nums)

def counts(words: List[str]) -> Dict[str, int]:
    return {w: len(w) for w in words}

The type inside brackets is the element type of the list or dict. Python 3.9+ allows lowercase list[int] and dict[str, int]; this lesson uses the typing module.

Nested types and reading them

Types can nest. List[Dict[str, int]] means a list whose items are dicts. This is useful for representing database rows or config settings.

When reading, parse right to left: find the innermost type, then add the outer container. Example: Dict[str, List[int]] is a dict with string keys and integer-list values.

Nested hints look complex, but IDEs and mypy follow them; you catch errors early.

Practice total function with List[int]

Write total(nums: List[int]) -> int. The body contains return sum(nums). Import List from typing. Call print(total([1, 2, 3])).

Starter code

main.py
# import List from typing
# total(nums: List[int]) -> int: sum the nums list
# print the result of total([1, 2, 3])

Sample solution

main.py
from typing import List

def total(nums: List[int]) -> int:
    return sum(nums)

print(total([1, 2, 3]))

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the container types

Term Meaning
List[int] List of integers
Dict[str, int] String→int dict
List[str] List of strings
Dict[str, str] String→string dict

2 Complete the Dict type

Question
from typing import Dict

def lengths(words):
    result: Dict[str, ____] = {}
    for w in words:
        result[w] = len(w)
    return result
Answer
from typing import Dict

def lengths(words):
    result: Dict[str, int] = {}
    for w in words:
        result[w] = len(w)
    return result

Explanation: Dict[str, int] is a dict with string keys and integer values; len(w) returns an integer.

3 What does Dict[str, int] describe?

  • A dict with string keys and integer values Correct answer
  • A list of integers
  • A dict containing only None
  • A list of strings

Explanation: Dict[str, int] is a dict with string keys and integer values.

All lessons in Advanced