Python List Type Hint: Using list[str] Correctly
Learn how to use Python list type hints with list[str], including syntax, function annotations, nested and mixed lists, common mistakes, and tooling compatibility.
![Illustration of a Python list with type hints showing list[str] annotation and a type checker shield.](https://kuehkhyqlimfiynlhpnt.supabase.co/storage/v1/object/public/post-thumbnails/posts/python-list-type-hint-15cfbe133dc143f6883d30e8611da913.webp)
Python list type hints use the built-in list type as a generic: list[str] describes a list whose elements are strings. This syntax is available on Python 3.9 and later, while older versions use typing.List[str]. The examples below cover the common ways to use list type hints in variables and functions, along with pitfalls to avoid.
The Basic Syntax for List Type Hints
The simplest form is list[str], which declares a list whose elements are all strings. For example:
names: list[str] = ['alice', 'bob', 'carol']The annotation tells type checkers and human readers that every element in this list should be a string. If you assign a list containing an integer, a static type checker such as mypy will report an error.
The same syntax works for other element types:
scores: list[int] = [95, 87, 91]
records: list[float] = [1.5, 2.7, 3.9]
flags: list[bool] = [True, False, True]For more complex element types, you can nest the generic notation. A list of dictionaries, for instance, would be list[dict[str, int]].
Why list[str] Replaced typing.List
Before Python 3.9, the standard way to annotate a list was typing.List:
from typing import List
names: List[str] = ['alice', 'bob']Python 3.9 introduced built-in collection types as generics, so list[str] became valid without importing anything. The typing.List form still works for backward compatibility, but it is no longer necessary in modern code.
The main advantage of list[str] is that it removes an import and aligns the annotation with the runtime type. list is what you actually use at runtime, and list[str] is what you write in annotations. This reduces cognitive overhead and makes the code cleaner.
If you support Python 3.8 or earlier, the built-in list does not support subscription, so an evaluated list[str] annotation raises a TypeError at runtime. Use typing.List in that case, or use from __future__ import annotations as described in the compatibility section below.
Annotating Function Parameters and Return Types
List type hints are most valuable in function signatures. They document the expected input and output without requiring the reader to trace the implementation.
def get_names() -> list[str]:
return ['alice', 'bob']
def process_names(names: list[str]) -> None:
for name in names:
print(name.upper())The return annotation -> list[str] states that the function returns a list of strings. The parameter annotation names: list[str] tells callers that only a list of strings is acceptable.
When a function modifies a list in place, the annotation should still reflect the element type. For example:
def add_name(names: list[str], name: str) -> None:
names.append(name)There is no need to annotate the return type as list[str] because the function returns None. The mutation is visible through the passed argument.
Nested Lists and Mixed Element Types
Lists can contain other lists, and the type hint should express that nesting. A matrix, for instance, is a list of lists of numbers:
matrix: list[list[int]] = [
[1, 2, 3],
[4, 5, 6],
]If you need a list that can hold multiple types, use Union or Any. For example, a list that contains either integers or strings:
from typing import Union
values: list[Union[int, str]] = [1, 'two', 3]In Python 3.10 and later, you can use the | operator instead of Union:
values: list[int | str] = [1, 'two', 3]This is more concise and works with modern type checkers. However, if you need to support Python 3.9, stick with Union.
A common mistake is to annotate a list as list without the element type. That is equivalent to list[Any] and disables most of the value that type hints provide. Always specify the element type unless you genuinely have no information about the contents.
Common Mistakes with List Type Hints
One frequent error is using list[str] in a context where the runtime object has a different type. For example, assigning a tuple to a variable annotated as list[str] will be flagged by a type checker, because a tuple is immutable and has a different type.
# Type checker error: tuple is not list
names: list[str] = ('alice', 'bob')Another mistake is forgetting that list[str] is a mutable type. If you pass a list to a function that only needs to read it, consider using Sequence[str] from typing to allow both lists and tuples. This gives callers more flexibility without sacrificing type safety.
from typing import Sequence
def print_names(names: Sequence[str]) -> None:
for name in names:
print(name)Using Sequence instead of list in read-only parameters is a good practice because it accepts any sequence, including tuples and ranges.
Another common issue is using list[str] as a default argument value. The annotation itself does not create a shared mutable object, but the default value still can:
def add_default(names: list[str] = []) -> None:
names.append('default')This code is valid but has the classic mutable default argument problem: the default list is shared across calls. Type hints do not change that behavior. Use None and create a new list inside the function to avoid the issue.
Runtime Behavior
Type hints are not enforced at runtime by default. For function parameters and return values, list[str] is stored in __annotations__, but Python does not check that the elements are strings when you call the function. This means type hints have no direct performance impact on normal execution.
With from __future__ import annotations, annotations are stored as strings and are not evaluated at function definition time. This can avoid constructing type objects at import time, but the practical difference is usually negligible. Code that inspects annotations at runtime must account for this by using typing.get_type_hints().
Because annotations are not enforced at runtime, adding list[str] is useful only when a static type checker is part of your workflow. Tools such as mypy, Pyright, and Pyre can catch mismatched element types before the code runs.
Compatibility and Tooling Support
list[str] requires Python 3.9 or later when annotations are evaluated normally. If your project supports Python 3.8 or earlier, use typing.List, or add from __future__ import annotations so the annotation is stored as a string and is not evaluated at function definition time:
from __future__ import annotations
def process_names(names: list[str]) -> None:
passWith the future import, this definition works on Python 3.8 even though the built-in list cannot be subscripted in that version. However, if you call typing.get_type_hints() on Python 3.8, it will try to evaluate the string list[str] and fail. For runtime annotation inspection on Python 3.8, stick with typing.List.
The widely used static type checkers support list[str] fully. Mypy, Pyright, and Pyre all understand the built-in generic syntax. On Python 3.9 and later, typing.get_type_hints() also resolves list[str] correctly.
When you use list[str] in a codebase that also uses older annotations, be consistent. Mixing list[str] and typing.List in the same project is valid, but it can confuse readers. Choose one style based on your minimum Python version and apply it consistently.
A final edge case worth knowing: list[str] is not the same as typing.List[str] at runtime. They are distinct objects, but they are treated as equivalent by type checkers. If you use typing.get_type_hints() to inspect annotations, you may get either form depending on how the annotation was written. This rarely matters in practice, but it can affect code that compares annotation objects directly.
For most projects, list[str] is the right choice. It is concise, requires no import, and works with the type checkers in common use. If you need to support older Python versions, typing.List remains a reliable fallback.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.