Explicit types for collections

The type checker cannot always infer the type of a list or adictionary. This often arises when creating an empty list ordictionary and assigning it to a new variable that doesn’t have an explicitvariable type. Here is an example where mypy can’t infer the typewithout some help:

  1. l = [] # Error: Need type annotation for 'l'

In these cases you can give the type explicitly using a type annotation:

  1. l: List[int] = [] # Create empty list with type List[int]
  2. d: Dict[str, int] = {} # Create empty dictionary (str -> int)

Similarly, you can also give an explicit type when creating an empty set:

  1. s: Set[int] = set()