Sling Academy
Home/Python/Python: Declaring Lists with Type Hints (7 Examples)

Python: Declaring Lists with Type Hints (7 Examples)

Last updated: July 04, 2023

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
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.append(2023)

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):
        self.name = 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.

Next Article: Python: Passing a List to a Function as Multiple Arguments

Previous Article: Python: Separate a List into Equally Sized Chunks

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs