Starting with Python 3.9, you can use list[str] as a type annotation, which doesn't require importing anything, as documented in PEP 585.

Python 3.5 standardizes the way function annotations are used for type hinting, as documented in PEP 484. To annotate a list of strings, you use List[str], where List is imported from the typing module. You can also use Sequence[str] if your function accepts any list-like sequence, or Iterable[str] for any iterable.

Python 3.4 and earlier doesn't specify a format for its function annotations, it merely provides a mechanism that allows you to use any expression as the annotation. How the annotations are interpreted is up to you and the libraries you use.

Answer from interjay on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
The type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment: ... Or marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment: from typing import TypeAlias Vector: TypeAlias = list[float]
Discussions

Question regarding type-hinting Collection types
So, logic says that here: list[str | int] It means that it's a list that contains ONLY strings OR ONLY integers. Right? Wrong, actually. This is a list of mixed str and int. What you mean would be written list[str] | list[int]. More on reddit.com
🌐 r/Python
10
8
August 26, 2023
Type Hints, can you indicate various types inside a list?
You could use List[Union[str, int]] for a list that contains strings and ints, but that is not what you have here. This is actually a list of tuples, each of which has a str and an int. For that you can use List[Tuple[str, int]] which specifically says that each tuple contains two items, the first of which is a string and the second an int. Also note that on Python 3.9+ you should use the built-in types rather than the ones defined in typing, so list[tuple[str, int]]. And note again that in your example list_of_grades[0] isn't a string, it's a tuple of (string, int). More on reddit.com
🌐 r/learnpython
7
2
November 15, 2021
Tuple-like typing for lists in type hints
Hello python devs, I always run into an issue like this while working with Union data, so like I know what elements will be in a list, but I don't think there's a way to type them, so I alw... More on github.com
🌐 github.com
1
October 1, 2022
What is too much type hinting for you?
Type-hinting the return type as None is great. Type-hinting "self: Self" is madness. More on reddit.com
🌐 r/Python
182
96
July 27, 2024
🌐
Mypy
mypy.readthedocs.io › en › stable › cheat_sheet_py3.html
Type hints cheat sheet - mypy 2.4.0 documentation
See Silencing type errors for details on how to silence errors. In typical Python code, many functions that can take a list or a dict as an argument only need their argument to be somehow “list-like” or “dict-like”. A specific meaning of “list-like” or “dict-like” (or ...
🌐
Reddit
reddit.com › r/python › question regarding type-hinting collection types
r/Python on Reddit: Question regarding type-hinting Collection types
August 26, 2023 -

I'm trying to make sense of the current type-hinting convention regarding Collection types. For simplicity's sake, I'll use list, tuple and dict, but that applies to any of their variant. Note that none of the following lines of code actually raise an error when run. Here's my question:

When someone writes:

var: str | int

What I read is obviously that 'var' is either a string OR an integer.

Again, when someone writes:

lst: list[str]

What I read is obviously that 'lst' is a list that contains ONLY strings.

So, logic says that here:

list[str | int]

It means that it's a list that contains ONLY strings OR ONLY integers. Right? And in this following case:

list[str, int]

it means that it's a list that contains strings AND/OR integers. Perhaps would it make more sense if it used & instead of , but whatever. Hopefully I'm making sense.

However, when checking the types using mypy, I find out that list[str, int] is not conventional, and that rather you should use list[str | int] for both cases. My code editor also says this, and yours probably does too.

Now take a similarly-structured type, tuple. By similarly-structured, I mean that you access and iterate through tuples the same way, in fact they are both Sequence types. The thing with tuple is that its args are index sensitive. I understand why this is the case and why it makes sense (because of immutability), but what doesn't make sense to me is why mypy is fine now with the comma notation with tuple but not list.

tpl: tuple[str, int] = ("", 0) # fine
tpl: tuple[str, int] = (0, "") # not fine
tpl: tuple[str | int] = (0, "") # not fine
tpl: tuple[str | int] = (0, ) # fine
tpl: tuple[str | int] = ("", ) # fine

Last but not least, dict. Everybody knows that Mapping types are different from Sequence types in the way you access, set or delete their items. So why is the typing convention this:

dict[str, int] # comma notation like tuple

and not:

dict[str: int] # Mapping specific notation 

The latter makes much more sense and is more readable to me, and makes the distinction between Sequence types and Mapping types. Furthermore, the use of commas in Mapping types kinda looks like you can insert as many of them as you want, just like tuple?

tpl: tuple[str, int] = ("", 0) # this is fine
tpl: tuple[str, int, bool] = ("", 0, False) # this is fine
dct: dict[str, int, bool] = {"": 0: False} # but this is not fine

I know that slices are not hashable for a reason, and that dict[str: int] notation kinda implies that they are, but again, the interpreter will raise no errors if you do this, much like if you write list[str, int], so I don't see the problem.

Is there an actual, good reason why this is the way it is?

Top answer
1 of 4
21
So, logic says that here: list[str | int] It means that it's a list that contains ONLY strings OR ONLY integers. Right? Wrong, actually. This is a list of mixed str and int. What you mean would be written list[str] | list[int].
2 of 4
10
You're looking at this purely from the perspective of a "user", and not the perspective of the "author". Let's pretend for a moment that the builtin class list doesn't exist, and you have to implement it. To do that, you need typing.Generic and, more importantly, a typing.TypeVar . The code would look more or less like this: T = typing.TypeVar('T') class List(typing.Generic[T]): def __init__(self): self._elements = [] def append(self, element: T) -> None: self._elements.append(element) As you can see, this class is generic over one TypeVar. So naturally, it also accepts one type argument: >>> List[int] # one argument __main__.List[int] >>> List[int | str] # still one argument __main__.List[int | str] >>> List[int, str] # two arguments TypeError: Too many arguments for ; actual 2, expected 1 (The reason why list[int, str] doesn't throw an error is because the python devs are lazy.) As for tuples, they serve a different purpose than lists. Lists are intended to be a homogeneous data structure, i.e. a sequence of an arbitrary number of items of the same type. Tuples, on the other hand, are intended to have a fixed number of items of (potentially) different types. So naturally tuple must accept an arbitrary number of type arguments. dict[str: int] # Mapping specific notation The latter makes much more sense and is more readable to me, and makes the distinction between Sequence types and Mapping types. This would make python's syntax and parser more complicated - and, frankly, inconsistent - for no real reason. As far as the type system is concerned, there is no difference between a sequence and a mapping. They're both just Generics, albeit with a different number of TypeVars.
🌐
Towards Data Science
towardsdatascience.com › home › data science › type hints in python
Type Hints in Python | Towards Data Science
July 11, 2023 - Type hints indicate the datatypes of both the inputs and outputs in functions (it applies to class methods as well). A problem many Python users complain about is the freedom we have to change a variable type.
🌐
Molssi
education.molssi.org › type-hints-pydantic-tutorial › chapters › TypeHintsInPython.html
Type Hints in Python — Python Type Hints, Dataclasses, and Pydantic
There is an important point to make about the difference between list and tuple as type hint. list are considered mutable objects in Python, so in our example the list[str] hint indicates the “list is of arbitrary length and every object is a string.” Because of this, list only accepts ...
Find elsewhere
🌐
Dagster
dagster.io › blog › python-type-hinting
Using Type Hinting in Python Projects
August 11, 2023 - In newer versions of Python, you can write list[str] instead of typing.List[int]. Type hints can be particularly useful when incorporated into function signatures.
🌐
Medium
medium.com › @palwishaakhtar › exploring-pythons-type-hints-and-checks-a3a062c66df3
Exploring Python’s Type Hints and Checks | by Palwisha Akhtar | Medium
April 16, 2024 - from typing import List def sum_of_list(l: List[float]): return sum(l) The Typing module extends Python’s type hinting capabilities beyond basic types to include more complex data structures and relationships. By utilizing advanced types such as List, Tuple, Dict, Sequence, Callable, Any, Optional, Union, and NoReturn, developers can precisely define the structures and behaviors of their code components.
🌐
FastAPI
fastapi.tiangolo.com › python-types
Python Types Intro - FastAPI
These "type hints" or annotations are a special syntax that allows declaring the type of a variable. By declaring types for your variables, editors and tools can give you better support. This is just a quick tutorial / refresher about Python type hints. It covers only the minimum necessary ...
🌐
flycoolman
flycoolman.com › coding › python › list-tuple-dict-vs-list-tuple-dict
list, tuple, dict vs List, Tuple, Dict | flycoolman
October 4, 2020 - You should always pick then non-typing generics whenever possible as the old typing.Tuple, typing.List and other generics are deprecated and will be removed in a later version of Python. What are type hints in Python 3.5? PEP 585 – Type Hinting Generics In Standard Collections typing — Support for type hints Using List/Tuple/etc.
🌐
W3Schools
w3schools.com › python › python_arguments.asp
Python Function Arguments
You can send any data type as an argument to a function (string, number, list, dictionary, etc.).
🌐
Reddit
reddit.com › r/learnpython › type hints, can you indicate various types inside a list?
r/learnpython on Reddit: Type Hints, can you indicate various types inside a list?
November 15, 2021 -

If I have a list that I know will have a certain type of object in the first element and a different type in the second. For instance, if I have a function that combines two lists and returns a lists of lists like so:

names = ["Brad Pitt", "Leonardo DiCaprio", "Henry Cavill", "Hugo Weaving"]
grades = [85,32,95,90]

def combine_lists():
    names_grades = []
    for i in range(0,4):
        names_grades.append(names[i],grades[i])
    return names_grades

Is it possible to type hint the return type so that it reflects the types in the list, something like this:

def combine_lists() ->List(str,int):

The point of this is that later I would be aware of the type I'm accessing when I try to read a specific element of the list for example:

list_of_grades = combine_lists()x = list_of_grades[0] #I want to know this is a string

🌐
Better Stack
betterstack.com › community › guides › scaling-python › python-type-hints
A Complete Guide to Python Type Hints | Better Stack Community
April 11, 2025 - You can annotate variables and ... {name}!" For collections such as lists and dictionaries, use the typing module to specify the types of their contents:...
🌐
GitHub
github.com › python › typing › issues › 1267
Tuple-like typing for lists in type hints · Issue #1267 · python/typing
October 1, 2022 - x: Dict[str, List[int, int]] = { "hi": [1, 2], "bye": [3, 1], "aaa": [79, 27], "haxxor": [1337, 420, 69], # error: Incompatible types in assignment (expression has type "List[int, int, int]", variable has type "List[int, int]") } Unions aren't as convenient... ... Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment ... topic: featureDiscussions about new features for Python's type annotationsDiscussions about new features for Python's type annotations
Author: python
🌐
iO Flood
ioflood.com › blog › python-type-hints
Python Type Hints: A Comprehensive Usage Guide
November 28, 2023 - As you become more proficient with Python type hints, you’ll discover that they offer a wealth of advanced features that can further enhance your code’s readability and robustness. Let’s delve into some of these advanced techniques. Generics are a powerful feature that allows you to specify type parameters for classes and functions, thereby creating reusable code components. Here’s an example: from typing import List, Tuple def process_data(data: List[Tuple[int, str]]) -> None: for item in data: print(f'Processing item {item[0]}: {item[1]}') process_data([(1, 'apple'), (2, 'banana')]) # Output: # Processing item 1: apple # Processing item 2: banana
🌐
GeeksforGeeks
geeksforgeeks.org › python › type-hints-in-python
Type Hints in Python - GeeksforGeeks
May 3, 2025 - Type hints are not enforced by the Python interpreter; they are purely for static analysis by external tools like mypy. So, even with type hints, the code will still run with errors unless a static type checker is used.
🌐
DEV Community
dev.to › decorator_factory › type-hints-in-python-tutorial-3pel
Get started with type hints in Python - DEV Community
June 19, 2025 - When you're assigning something to a variable, the type checker (remember — just a tool, separate from Python) will infer the type of the variable. Inference is not "guessing" as the name may suggest. A more correct synonym would be deduction — figuring the type precisely by following an algorithm. All the types you're familiar with — int, str, float, range, list etc. — are valid type hints.
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 207771425-Type-hinting-list-of-objects
Type hinting list of objects – IDEs Support (IntelliJ Platform) | JetBrains
August 3, 2016 - And in Python 2/3 compatible code you can use the alternative approach with special "#type:" comments: from typing import Iterable from models import ContactList class Contacts: def get_contact_lists(self): # type: () -> Iterable[ContactList] return undefined() ... Perfect, thanks that helps a lot. ... I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
🌐
Medium
medium.com › @AlexanderObregon › how-pythons-type-hinting-and-annotations-work-319d952247a6
How Python’s Type Hinting and Annotations Work | Medium
July 14, 2024 - The typing module in Python provides a rich set of tools for working with type hints. It includes classes and functions for specifying complex types, such as generics, unions, and callable types. Generics allow you to specify types that work with a range of other types. For example, you can use List to specify a list of elements of a specific type: