As of May 2015, PEP 484 (Type Hints) has been formally accepted. The draft implementation is also available at github under ambv/typehinting.

In September 2015, Python 3.5 was released with support for Type Hints and includes a new typing module. This allows for the specification of types contained within collections. As of November 2015, JetBrains PyCharm 5.0 fully supports Python 3.5 to include Type Hints as illustrated below.

from typing import List

def do_something(l: List[str]):
    for s in l:
        s  # str

Original Answer

As of Aug 2014, I have confirmed that it is not possible to use Python 3 type annotations to specify types within collections (ex: a list of strings).

The use of formatted docstrings such as reStructuredText or Sphinx are viable alternatives and supported by various IDEs.

It also appears that Guido is mulling over the idea of extending type annotations in the spirit of mypy: http://mail.python.org/pipermail/python-ideas/2014-August/028618.html

Answer from Eric W. on Stack Overflow
๐ŸŒ
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 # Initialised using square brackets my_empty_list: List[Any] = [] print(my_empty_list) my_list_of_integers: List[int] = [1,2,3,4] print(my_list_of_integers) my_list_of_floats: List[float] = [1.2, 3.4, 5.6] print(my_list_of_floats) my_list_of_strings: List[str] =["this", "is" ,"a" ,"string"] print(my_list_of_strings) my_list_of_booleans: List[bool] =[True,False,False,True] print(my_list_of_booleans) my_mixed_list: List[Any] = [1, "Hello", False, 1.23] print(my_mixed_list)
Top answer
1 of 5
346

As of May 2015, PEP 484 (Type Hints) has been formally accepted. The draft implementation is also available at github under ambv/typehinting.

In September 2015, Python 3.5 was released with support for Type Hints and includes a new typing module. This allows for the specification of types contained within collections. As of November 2015, JetBrains PyCharm 5.0 fully supports Python 3.5 to include Type Hints as illustrated below.

from typing import List

def do_something(l: List[str]):
    for s in l:
        s  # str

Original Answer

As of Aug 2014, I have confirmed that it is not possible to use Python 3 type annotations to specify types within collections (ex: a list of strings).

The use of formatted docstrings such as reStructuredText or Sphinx are viable alternatives and supported by various IDEs.

It also appears that Guido is mulling over the idea of extending type annotations in the spirit of mypy: http://mail.python.org/pipermail/python-ideas/2014-August/028618.html

2 of 5
228

As of Python 3.9, builtin types are generic with respect to type annotations (see PEP 585). This allows to directly specify the type of elements:

def my_func(l: list[int]):
    pass

This also extends to most other container types of the standard library, for example collections.deque or collections.abc.Mapping.


Various tools may support this syntax earlier than Python 3.9. When annotations are not inspected at runtime, the syntax is valid using quoting or __future__.annotations.

# quoted
def my_func(l: 'list[int]'):
    pass
# postponed evaluation of annotation
from __future__ import annotations

def my_func(l: list[int]):
    pass

As a consequence of PEP 585, most helpers in typing corresponding to standard library types are deprecated, such as typing.List, typing.Deque or typing.Mapping. They should only be used if compatibility with Python versions prior to 3.9 is required.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to type hint a list of two lists of strings? or maybe suggest a better data structure?
r/learnpython on Reddit: How to type hint a list of two lists of strings? Or maybe suggest a better data structure?
January 10, 2022 -

I like to refactor my Advent of Code solutions over time to see where I could have done things differently, especially as I pick up new ideas.

2021's day 8 input has many lines of input that look like this:

acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf

Two lists of space separated groups of letters which are, in turn, separated by "|".

My code to get the input looks like this:

entries = []
    with open("input/input_08.txt") as file:
        for signal, output in (ln.strip().split(" | ") for ln in file):
            entries.append([signal.split(), output.split()])

How should I type hint entries? I'd like to do something like:

entries: list[list[str],list[str]] = []

But, that doesn't work. When I look at the mypy docs and cheatsheet or the Python docs and hinting PEPs, I can't really see how I should be hinting a structure like this. Is there a way to do it? Should I be using a different structure?

๐ŸŒ
Daily Dose of DS
blog.dailydoseofds.com โ€บ p โ€บ 10-ways-to-declare-type-hints-in
10 Ways to Declare Type Hints in Python - by Avi Chawla
March 26, 2024 - For instance, grade may only take values from a fixed set of grades. ... Some objects could be of any type โ€” list, int, string, etc. Declare them as follows: ... To specify type hints for its parameters. To specify the type hint for the object returned by the function. You can use any of the above discussed type hints to declare type hints in functions โ€” Any, Union, Iterable, Optional etc. At times, a function may have another function as its parameters. This happens all the time in Python ...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_type_hints.htm
Python - Type Hints
In Python when using type hints to specify basic types we can simply use the name of the type as the annotation. Following is the example of using the basic data types such as integer, float, string etc โˆ’
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ type hints in python
Type Hints in Python | Towards Data Science
January 16, 2025 - Its keys are tuples and its values are nested dictionaries with string keys and set values. Good luck trying to remember that when you revisit the code some months later! The good part is that type hints are extremely easy to understand and easy to use. We have no excuse not to use them, and there are no perks in not doing so. So, letโ€™s go ahead and start seeing some code. Iโ€™ll be using Python 3.11, but most of the examples will work on previous versions of Python 3.
๐ŸŒ
Pyrefly
pyrefly.org โ€บ python typing 101
Python Typing 101 | Pyrefly
A gentle, exampleโ€‘driven introduction to static type hints in Python.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ type-hints-in-python
Type Hints in Python - GeeksforGeeks
May 3, 2025 - Tuple[str, int]: The get_name_and_age function returns a tuple with a string and an integer. Hereโ€™s an example of a factorial function without type hints:
๐ŸŒ
Josh Di Mella
joshdimella.com โ€บ blog โ€บ python-typing-best-practices
Python Type Hints: A Comprehensive Guide to Using Type Annotations in Python | Josh Di Mella | Software Engineer
June 5, 2023 - Python provides a set of built-in types like int, float, str, list, dict, etc. Additionally, you can also use type hints with user-defined classes and modules. Here are some additional examples showcasing the benefits of Python type hints: # Type hint for a function that takes a list of integers and returns a list of strings def process_numbers(numbers: List[int]) -> List[str]: return [str(num) for num in numbers] # Type hint for a function that takes a dictionary with string keys and integer values def calculate_total(data: Dict[str, int]) -> int: return sum(data.values()) # Type hint for a f
๐ŸŒ
Better Stack
betterstack.com โ€บ community โ€บ guides โ€บ scaling-python โ€บ python-type-hints
A Complete Guide to Python Type Hints | Better Stack Community
In the example above, process_input accepts either a string or a byte string (str or bytes). The function logic adapts based on the input type, handling both cases safely. ... More expressive: Readers understand the range of valid inputs or outputs at a glance. Safer: Tools like mypy can alert you when you're not handling all possible cases (e.g., forgetting to check for None). Cleaner: You avoid long comments or confusing docstrings โ€” the types speak for themselves. These hints are compelling when combined with static analysis tools or in larger codebases where assumptions about types can easily lead to bugs.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ typing.html
typing โ€” Support for type hints
1 week ago - Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements. from collections.abc import Mapping, Sequence class Employee: ... # Sequence[Employee] indicates that all elements in the sequence # must be instances of "Employee". # Mapping[str, str] indicates that all keys and all values in the mapping # must be strings.
๐ŸŒ
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
๐ŸŒ
JetBrains
jetbrains.com โ€บ help โ€บ pycharm โ€บ type-hinting-in-product.html
Type hinting in PyCharm | PyCharm Documentation
October 21, 2025 - Select Add type hint for .... Press Enter to complete the action or edit the type if appropriate. You can also use Python stubs to specify the types of variables, functions, and class fields.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python basics โ€บ python type hints
Python Type Hints
April 2, 2025 - The error indicates that the argument of the say_hi is int while the expected type is str. If you change back the argument to a string and run the mypy again, itโ€™ll show a success message: Success: no issues found in 1 source fileCode language: Python (python) When defining a variable, you can add a type hint like this:
๐ŸŒ
Python
peps.python.org โ€บ pep-0484
PEP 484 โ€“ Type Hints | peps.python.org
A TypeVar() expression must always directly be assigned to a variable (it should not be used as part of a larger expression). The argument to TypeVar() must be a string equal to the variable name to which it is assigned. Type variables must not be redefined. TypeVar supports constraining parametric types to a fixed set of possible types (note: those types cannot be parameterized by type variables).
๐ŸŒ
Dagster
dagster.io โ€บ blog โ€บ python-type-hinting
Using Type Hinting in Python Projects
The typing module in Python provides several classes that can be used to provide more complex type hints. Below are some of the most commonly used classes: The list, dict, tuple, and set classes can be used to provide type hints for lists, dictionaries, tuples, and sets respectively. They can be parameterized to provide even more detailed type hints. ### A list of integers numbers: list[int] = [1, 2, 3] ### A dictionary with string keys and float values weights: dict[str, float] = {"apple": 0.182, "banana": 0.120} ### A tuple with an integer and a string student: tuple[int, str] = (1, "John") ### A set of strings flags: set[str] = {"apple", "banana", "cherry"}
๐ŸŒ
Real Python
realpython.com โ€บ python-type-hints-multiple-types
How to Use Type Hints for Multiple Return Types in Python โ€“ Real Python
March 8, 2024 - So, the return value of this function is either a string containing the username or None if the email address is incomplete. The type hint for the return value uses the pipe operator (|) to indicate alternative types of the single value that the function returns. To define the same function in Python versions older than 3.10, you can use an alternative syntax:
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ understanding type annotation in python
Understanding type annotation in Python - LogRocket Blog
June 4, 2024 - In Python, you can define a variable with a type hint using the following syntax: ... You assign a string value "rocket" to the name variable.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.3 documentation
1 week ago - Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_string_formatting.asp
Python String Formatting
To specify a string as an f-string, simply put an f in front of the string literal, like this: ... To format values in an f-string, add placeholders {}, a placeholder can contain variables, operations, functions, and modifiers to format the value. ... A placeholder can also include a modifier to format the value. A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals: ... You can perform Python operations inside the placeholders.