Python: Declaring Lists with Type Hints (7 Examples)

Updated: July 4, 2023 By: Khue Post a comment

In Python 3.5 and above, when working with lists (especially complex lists), you can use type hints to clarify the expected type of list elements, enable static type-checking tools (such as type checkers, IDEs, linters, etc) to catch type-related errors, and provide documentation for other developers working on the code (if any).

This succinct, practical article will walk you through some examples of using type hints with Python lists in order from basic to advanced.

Basic List of Integers

from typing import List

# Declare an empty list that will hold integers
my_list: List[int] = []

# Add 5 integers to the list

List of Strings

from typing import List

# Declare a list of strings
my_list: List[str] = ['apple', 'banana', 'cherry']

List of Mixed Types

from typing import List, Union

# Declare a list of mixed types (integers and strings)
my_list: List[Union[int, str]] = [1, 'apple', 2, 'banana']

Nested List

from typing import List

# Declare a nested list of integers
my_list: List[List[int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

List of Tuples

from typing import List, Tuple

# Declare a list of tuples containing strings and integers
my_list: List[Tuple[str, int]] = [('apple', 1), ('banana', 2), ('cherry', 3)]

List of Custom Objects

from typing import List

# Define a custom class
class MyClass:
    def __init__(self, name: str, value: int): = name
        self.value = value

# Declare a list of custom objects
my_list: List[MyClass] = [MyClass('obj1', 1), MyClass('obj2', 2), MyClass('obj3', 3)]

List of Dictionaries

from typing import List, Dict, Union

# Declare a list of dictionaries with mixed value types
my_list: List[Dict[str, Union[str, int, float, bool]]] = [
    {'name': 'John', 'age': 25, 'score': 78.5, 'is_passed': True},
    {'name': 'Jane', 'age': 30, 'score': 92.3, 'is_passed': True},
    {'name': 'Bob', 'age': 27, 'score': 65.9, 'is_passed': False}

It is important to note that type hints are not runtime-enforced, and modifications to the list can still be made at runtime.