Array Type Hinting in Python: From Basics to Best Practices
When working with arrays, type hints specify the expected data structure to help you catch errors earlier.
Let’s dive into array type hinting with practical examples.
Basic Syntax for Array Type Hinting
You can use the List
type from the typing
module to hint at arrays containing a single data type.
from typing import List def calculate_average(grades: List[float]) -> float: return sum(grades) / len(grades) grades = [85.5, 90.0, 78.5, 92.0] print(calculate_average(grades))
Output:
86.5
This function hints that grades
must be a list of floats. It calculates the average of the input list and returns the result as a float.
Type Hinting for Arrays of Specific Types
To ensure a function works with arrays of specific types, explicitly define the type within the List
.
from typing import List def generate_usernames(names: List[str]) -> List[str]: return [name.lower().replace(" ", "_") for name in names] users = ["Ahmed Ali", "Sara Adel", "Youssef Said"] print(generate_usernames(users))
Output:
['ahmed_ali', 'sara_adel', 'youssef_said']
The function expects a list of strings (names
) and returns a new list of formatted usernames.
Type Hinting for Multidimensional Arrays
For multidimensional arrays, use nested List
type hints.
from typing import List def sum_matrix(matrix: List[List[int]]) -> int: return sum(sum(row) for row in matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(sum_matrix(matrix))
Output:
45
The hint specifies a two-dimensional list of integers. The function computes the total sum of all integers in the matrix.
Type Hinting for Variable-Length Arrays
When you don’t need to limit input strictly to lists, use Sequence
or Iterable
.
from typing import Sequence def get_first_and_last(elements: Sequence[int]) -> Sequence[int]: return elements[0], elements[-1] data = (10, 20, 30, 40) # Tuple, not a list print(get_first_and_last(data))
Output:
(10, 40)
This function works with any ordered collection like tuples or lists, thanks to the flexible Sequence
type hint.
Common Pitfalls and How to Avoid Them
Mixing mutable and immutable types
Avoid mixing mutable (list
) and immutable (tuple
) types in your hints to prevent unexpected behavior.
from typing import Union, List, Tuple def validate_input(data: Union[List[int], Tuple[int]]) -> bool: return all(isinstance(x, int) for x in data) print(validate_input([1, 2, 3])) print(validate_input((4, 5, 6)))
Output:
True True
The Union
hint allows either lists or tuples of integers. The function validates that all elements are integers, regardless of the input type.
Over-specifying vs. under-specifying types
Over-specifying types can make the code too restrictive, while under-specifying can lead to ambiguity.
from typing import Iterable def find_max(values: Iterable[int]) -> int: return max(values) values_set = {10, 20, 5, 30} # A set, not a list print(find_max(values_set))
Output:
30
Using Iterable
instead of List
ensures the function works with any collection that can be iterated, including sets.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.