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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots