Until Python 3.9 added support for type hinting using standard collections, you had to use typing.Tuple and typing.List if you wanted to document what type the contents of the containers needed to be:

def f(points: Tuple[float, float]):
    return map(do_stuff, points)

Up until Python 3.8, tuple and list did not support being used as generic types. The above example documents that the function f requires the points argument to be a tuple with two float values.

typing.Tuple is special here in that it lets you specify a specific number of elements expected and the type of each position. Use ellipsis if the length is not set and the type should be repeated: Tuple[float, ...] describes a variable-length tuple with floats.

For typing.List and other sequence types you generally only specify the type for all elements; List[str] is a list of strings, of any size. Note that functions should preferentially take typing.Sequence as arguments and typing.List is typically only used for return types; generally speaking most functions would take any sequence and only iterate, but when you return a list, you really are returning a specific, mutable sequence type.

If you still need to support Python 3.8 or older code, you should always pick the typing generics even when you are not currently restricting the contents. It is easier to add that constraint later with a generic type as the resulting change will be smaller.

If you are implementing a custom container type and want that type to support generics, you can implement a __class_getitem__ hook or inherit from typing.Generic (which in turn implements __class_getitem__).

Answer from Martijn Pieters on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
1 week ago - For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example: from collections.abc import Mapping # Type checker will infer that all elements in ``x`` are meant to be ints x: list[int] = [] # Type checker error: ``list`` only accepts a single type argument: y: list[int, str] = [1, 'foo'] # Type checker will infer that all keys in ``z`` are meant to be strings, # and that all values in ``z`` are meant to be either strings or ints z: Mapping[str, str | int] = {}
Top answer
1 of 3
349

Until Python 3.9 added support for type hinting using standard collections, you had to use typing.Tuple and typing.List if you wanted to document what type the contents of the containers needed to be:

def f(points: Tuple[float, float]):
    return map(do_stuff, points)

Up until Python 3.8, tuple and list did not support being used as generic types. The above example documents that the function f requires the points argument to be a tuple with two float values.

typing.Tuple is special here in that it lets you specify a specific number of elements expected and the type of each position. Use ellipsis if the length is not set and the type should be repeated: Tuple[float, ...] describes a variable-length tuple with floats.

For typing.List and other sequence types you generally only specify the type for all elements; List[str] is a list of strings, of any size. Note that functions should preferentially take typing.Sequence as arguments and typing.List is typically only used for return types; generally speaking most functions would take any sequence and only iterate, but when you return a list, you really are returning a specific, mutable sequence type.

If you still need to support Python 3.8 or older code, you should always pick the typing generics even when you are not currently restricting the contents. It is easier to add that constraint later with a generic type as the resulting change will be smaller.

If you are implementing a custom container type and want that type to support generics, you can implement a __class_getitem__ hook or inherit from typing.Generic (which in turn implements __class_getitem__).

2 of 3
189

From Python 3.9 (PEP 585) onwards tuple, list and various other classes are now generic types. Using these rather than their typing counterpart is now preferred. From Python 3.9 you can now just do:

def f(points: tuple[float, float]):
    return map(do_stuff, points)

If you don't need to evaluate your type hints then you can use this syntax in Python 3.7+ due to PEP 563.

from __future__ import annotations


def f(points: tuple[float, float]):
    return map(do_stuff, points)

You should always pick then non-typing generic whenever possible as the old typing.Tuple, typing.List and other generics are deprecated and will be removed in a later version of Python.

Importing those from typing is deprecated. Due to PEP 563 and the intention to minimize the runtime impact of typing, this deprecation will not generate DeprecationWarnings. Instead, type checkers may warn about such deprecated usage when the target version of the checked program is signalled to be Python 3.9 or newer. It's recommended to allow for those warnings to be silenced on a project-wide basis.

The deprecated functionality will be removed from the typing module in the first Python version released 5 years after the release of Python 3.9.0.

Discussions

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
How to type hint a list of two lists of strings? Or maybe suggest a better data structure?
This isn't just a list of two lists of strings. It's a list that contains lists that contain two lists of strings. That could be type-hinted as list[list[list[str]]], though that doesn't express that one of those lists is specifically a pair. For that, you want to use tuples (entries.append((signal.split(), output.split()))), then you can type-hint as list[tuple[list[str], list[str]]]. More on reddit.com
🌐 r/learnpython
5
0
January 10, 2022
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
🌐
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

🌐
FastAPI
fastapi.tiangolo.com › python-types
Python Types Intro - FastAPI
As the list is a type that contains some internal types, you put them in square brackets: Python 3.10+ def process_items(items: list[str]): for item in items: print(item) Info · Those internal types in the square brackets are called "type parameters". In this case, str is the type parameter passed to list.
🌐
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.
🌐
Mypy
mypy.readthedocs.io › en › stable › cheat_sheet_py3.html
Type hints cheat sheet - mypy 1.19.1 documentation
# For most types, just use the name of the type in the annotation # Note that mypy can usually infer the type of a variable from its value, # so technically these annotations are redundant x: int = 1 x: float = 1.0 x: bool = True x: str = "test" x: bytes = b"test" # For collections on Python 3.9+, the type of the collection item is in brackets x: list[int] = [1] x: set[int] = {6, 7} # For mappings, we need the types of both keys and values x: dict[str, float] = {"field": 2.0} # Python 3.9+ # For tuples of fixed size, we specify the types of all the elements x: tuple[int, str, float] = (3, "yes
Find elsewhere
🌐
Medium
mrslima.medium.com › python-typing-88923684500b
Python Typing. Annotations & Type Hints for Python 3.5… | by Daniela Lima | Medium
October 6, 2021 - So a lot of times when you are writing a function, in Python, you want one of the parameters to be anything that’s a sequence, you don’t care what type of sequence it is. You just want it to be a sequence. You’ll be needing this there’s no way to specify, if the parameter should be a list or a tuple.
🌐
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... ... topic: featureDiscussions about new features for Python's type annotationsDiscussions about new features for Python's type annotations
Published   Oct 01, 2022
🌐
Wamaithanyamu
wamaithanyamu.com › python-lists
Using Lists in python with type hints
July 4, 2022 - # Import the type hint module # Any means the List will take in any type of data type from typing import List, Any # Initialized using the list constructor my_empty_list: List[Any] = list() print(my_empty_list) my_list_of_integers: List[int] = list((1,2,3,4)) print(my_list_of_integers) my_list_of_floats: List[float] =list ((1.2, 3.4, 5.6)) print(my_list_of_floats) my_list_of_strings: List[str]=list (("this", "is" ,"a" ,"string")) print(my_list_of_strings) my_list_of_booleans: List[bool] =list((True, False,False,True)) print(my_list_of_booleans) my_mixed_list: List[Any]= list((1, "Hello", False, 1.23)) print(my_mixed_list)
🌐
Adarshd
blog.adarshd.dev › posts › til-list-from-typing-module-is-inheritable
List from Typing module is inheritable | Blog | Adarsh Divakaran
December 20, 2023 - This _alias creates List as a child instance of _BaseGenericAlias. See that the inst attribute is set to False above. Now, let’s take a look at the _BaseGenericAlias class: The call dunder is overridden to raise a type error if the _inst attribute of the alias is False.
🌐
Real Python
realpython.com › python-type-checking
Python Type Checking (Guide) – Real Python
July 15, 2024 - The typing.Type[] construct is the typing equivalent of type(). You need it to note that the class method expects a class and returns an instance of that class. In the object oriented version of the game, we added the option to name the players on the command line. This is done by listing player names after the name of the program: ... $ python game.py GeirArne Dan Joanna Dan: ♢A Joanna: ♡9 P1: ♣A GeirArne: ♣2 Dan: ♡A Joanna: ♡6 P1: ♠4 GeirArne: ♢8 Dan: ♢K Joanna: ♢Q P1: ♣K GeirArne: ♠5 Dan: ♡2 Joanna: ♡J P1: ♠7 GeirArne: ♡K Dan: ♢10 Joanna: ♣3 P1: ♢4 Geir
🌐
Dagster
dagster.io › blog › python-type-hinting
Using Type Hinting in Python Projects
In Python, there is a distinction between atomic and composite types when it comes to type hinting. Atomic types, such as int, float, and str, are simple and indivisible, and their type annotations can be provided directly using the type itself, like str. def my_function(my_string: str) -> int: return len(my_string) On the other hand, composite types like List and Dict are composed of other types, and before Python 3.9, they often required importing specific definitions from the typing module, such as typing.List[int] for a list of integers.
🌐
Pybites
pybit.es › articles › code-better-with-type-hints-part-2
Code Better With Type Hints – Part 2 - Pybites
August 30, 2021 - For example, typing.List is the correct type hint for the list type. However, since Python 3.9 some of these data types can be used directly as type hints, so list[int] is allowed in Python 3.9 but has to be List[int] in previous versions.
🌐
Python
typing.python.org › en › latest › spec › tuples.html
Tuples — typing documentation
This enables us to specify types such as tuple[int, *tuple[str, ...], str] – a tuple type where the first element is guaranteed to be of type int, the last element is guaranteed to be of type str, and the elements in the middle are zero or more elements of type str.
🌐
Hacker News
news.ycombinator.com › item
what's the difference between list and List, dict and Dict and Mapping? | Hacker News
December 12, 2018 - So typing.List exists to be a subscriptable object you can use when annotating, and "typing.List[int]" works. Same for the other names · list[int] TypeError: 'type' object has no attribute '__getitem__'
🌐
W3Schools
w3schools.com › python › python_datatypes.asp
Python Data Types
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... In programming, data type is an important concept.
🌐
W3Schools
w3schools.com › python › python_lists_methods.asp
Python - List Methods
Python Variables Variable Names ... Data Types ... Python Strings Slicing Strings Modify Strings Concatenate Strings Format Strings Escape Characters String Methods String Exercises Code Challenge Python Booleans ... Python Operators Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge Python Lists...
🌐
Google
google.github.io › styleguide › pyguide.html
Google Python Style Guide
You can annotate Python code with type hints. Type-check the code at build time with a type checking tool like pytype. In most cases, when feasible, type annotations are in source files.