The other answers have done a good job at explaining duck typing and the simple answer by tzot:

Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.

However, one interesting thing has changed since 2010 (when the question was first asked), namely the implementation of PEP 3107 (implemented in Python 3). You can now actually specify the type of a parameter and the type of the return type of a function like this:

def pick(l: list, index: int) -> int:
    return l[index]

Here we can see that pick takes 2 parameters, a list l and an integer index. It should also return an integer.

So here it is implied that l is a list of integers which we can see without much effort, but for more complex functions it can be a bit confusing as to what the list should contain. We also want the default value of index to be 0. To solve this you may choose to write pick like this instead:

def pick(l: "list of ints", index: int = 0) -> int:
    return l[index]

Note that we now put in a string as the type of l, which is syntactically allowed, but it is not good for parsing programmatically (which we'll come back to later).

It is important to note that Python won't raise a TypeError if you pass a float into index, the reason for this is one of the main points in Python's design philosophy: "We're all consenting adults here", which means you are expected to be aware of what you can pass to a function and what you can't. If you really want to write code that throws TypeErrors you can use the isinstance function to check that the passed argument is of the proper type or a subclass of it like this:

def pick(l: list, index: int = 0) -> int:
    if not isinstance(l, list):
        raise TypeError
    return l[index]

More on why you should rarely do this and what you should do instead is talked about in the next section and in the comments.

PEP 3107 does not only improve code readability but also has several fitting use cases which you can read about here.


Type annotation got a lot more attention in Python 3.5 with the introduction of PEP 484 which introduces a standard module typing for type hints.

These type hints came from the type checker mypy (GitHub), which is now PEP 484 compliant.

The typing module comes with a pretty comprehensive collection of type hints, including:

  • List, Tuple, Set, Dict - for list, tuple, set and dict respectively.
  • Iterable - useful for generators.
  • Any - when it could be anything.
  • Union - when it could be anything within a specified set of types, as opposed to Any.
  • Optional - when it might be None. Shorthand for Union[T, None].
  • TypeVar - used with generics.
  • Callable - used primarily for functions, but could be used for other callables.

These are the most common type hints. A complete listing can be found in the documentation for the typing module.

Here is the old example using the annotation methods introduced in the typing module:

from typing import List

def pick(l: List[int], index: int) -> int:
    return l[index]

One powerful feature is the Callable which allows you to type annotate methods that take a function as an argument. For example:

from typing import Callable, Any, Iterable

def imap(f: Callable[[Any], Any], l: Iterable[Any]) -> List[Any]:
    """An immediate version of map, don't pass it any infinite iterables!"""
    return list(map(f, l))

The above example could become more precise with the usage of TypeVar instead of Any, but this has been left as an exercise to the reader since I believe I've already filled my answer with too much information about the wonderful new features enabled by type hinting.


Previously when one documented Python code with for example Sphinx some of the above functionality could be obtained by writing docstrings formatted like this:

def pick(l, index):
    """
    :param l: list of integers
    :type l: list
    :param index: index at which to pick an integer from *l*
    :type index: int
    :returns: integer at *index* in *l*
    :rtype: int
    """
    return l[index]

As you can see, this takes a number of extra lines (the exact number depends on how explicit you want to be and how you format your docstring). But it should now be clear to you how PEP 3107 provides an alternative that is in many (all?) ways superior. This is especially true in combination with PEP 484 which, as we have seen, provides a standard module that defines a syntax for these type hints/annotations that can be used in such a way that it is unambiguous and precise yet flexible, making for a powerful combination.

In my personal opinion, this is one of the greatest features in Python ever. I can't wait for people to start harnessing the power of it. Sorry for the long answer, but this is what happens when I get excited.


An example of Python code which heavily uses type hinting can be found here.

Answer from erb on Stack Overflow
Top answer
1 of 14
1153

The other answers have done a good job at explaining duck typing and the simple answer by tzot:

Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.

However, one interesting thing has changed since 2010 (when the question was first asked), namely the implementation of PEP 3107 (implemented in Python 3). You can now actually specify the type of a parameter and the type of the return type of a function like this:

def pick(l: list, index: int) -> int:
    return l[index]

Here we can see that pick takes 2 parameters, a list l and an integer index. It should also return an integer.

So here it is implied that l is a list of integers which we can see without much effort, but for more complex functions it can be a bit confusing as to what the list should contain. We also want the default value of index to be 0. To solve this you may choose to write pick like this instead:

def pick(l: "list of ints", index: int = 0) -> int:
    return l[index]

Note that we now put in a string as the type of l, which is syntactically allowed, but it is not good for parsing programmatically (which we'll come back to later).

It is important to note that Python won't raise a TypeError if you pass a float into index, the reason for this is one of the main points in Python's design philosophy: "We're all consenting adults here", which means you are expected to be aware of what you can pass to a function and what you can't. If you really want to write code that throws TypeErrors you can use the isinstance function to check that the passed argument is of the proper type or a subclass of it like this:

def pick(l: list, index: int = 0) -> int:
    if not isinstance(l, list):
        raise TypeError
    return l[index]

More on why you should rarely do this and what you should do instead is talked about in the next section and in the comments.

PEP 3107 does not only improve code readability but also has several fitting use cases which you can read about here.


Type annotation got a lot more attention in Python 3.5 with the introduction of PEP 484 which introduces a standard module typing for type hints.

These type hints came from the type checker mypy (GitHub), which is now PEP 484 compliant.

The typing module comes with a pretty comprehensive collection of type hints, including:

  • List, Tuple, Set, Dict - for list, tuple, set and dict respectively.
  • Iterable - useful for generators.
  • Any - when it could be anything.
  • Union - when it could be anything within a specified set of types, as opposed to Any.
  • Optional - when it might be None. Shorthand for Union[T, None].
  • TypeVar - used with generics.
  • Callable - used primarily for functions, but could be used for other callables.

These are the most common type hints. A complete listing can be found in the documentation for the typing module.

Here is the old example using the annotation methods introduced in the typing module:

from typing import List

def pick(l: List[int], index: int) -> int:
    return l[index]

One powerful feature is the Callable which allows you to type annotate methods that take a function as an argument. For example:

from typing import Callable, Any, Iterable

def imap(f: Callable[[Any], Any], l: Iterable[Any]) -> List[Any]:
    """An immediate version of map, don't pass it any infinite iterables!"""
    return list(map(f, l))

The above example could become more precise with the usage of TypeVar instead of Any, but this has been left as an exercise to the reader since I believe I've already filled my answer with too much information about the wonderful new features enabled by type hinting.


Previously when one documented Python code with for example Sphinx some of the above functionality could be obtained by writing docstrings formatted like this:

def pick(l, index):
    """
    :param l: list of integers
    :type l: list
    :param index: index at which to pick an integer from *l*
    :type index: int
    :returns: integer at *index* in *l*
    :rtype: int
    """
    return l[index]

As you can see, this takes a number of extra lines (the exact number depends on how explicit you want to be and how you format your docstring). But it should now be clear to you how PEP 3107 provides an alternative that is in many (all?) ways superior. This is especially true in combination with PEP 484 which, as we have seen, provides a standard module that defines a syntax for these type hints/annotations that can be used in such a way that it is unambiguous and precise yet flexible, making for a powerful combination.

In my personal opinion, this is one of the greatest features in Python ever. I can't wait for people to start harnessing the power of it. Sorry for the long answer, but this is what happens when I get excited.


An example of Python code which heavily uses type hinting can be found here.

2 of 14
228

Python is strongly typed because every object has a type, every object knows its type, it's impossible to accidentally or deliberately use an object of a type "as if" it was an object of a different type, and all elementary operations on the object are delegated to its type.

This has nothing to do with names. A name in Python doesn't "have a type": if and when a name's defined, the name refers to an object, and the object does have a type (but that doesn't in fact force a type on the name: a name is a name).

A name in Python can perfectly well refer to different objects at different times (as in most programming languages, though not all) -- and there is no constraint on the name such that, if it has once referred to an object of type X, it's then forevermore constrained to refer only to other objects of type X. Constraints on names are not part of the concept of "strong typing", though some enthusiasts of static typing (where names do get constrained, and in a static, AKA compile-time, fashion, too) do misuse the term this way.

🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
The argument list must be a list of types, a ParamSpec, Concatenate, or an ellipsis (...). The return type must be a single type. If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable: def concat(x: str, y: str) -> str: return x + y x: Callable[..., str] x = str # OK x = concat # Also OK · Callable cannot express complex signatures such as functions that take a variadic number of arguments, overloaded functions, or functions that have keyword-only parameters.
Discussions

Explicit parameter list in function documentation - Documentation - Discussions on Python.org
I prefer the parameters of a function (with their documentation) to be listed explicitly in the function’s documentation. This is in contrast with man-style, which describes the positionals in prose. Compare open (what I call man-style) with numpy.linalg.norm (what I say employs an explicit list). More on discuss.python.org
🌐 discuss.python.org
7
May 31, 2022
Why isn´t the parameter of the function of type list?
You're recursively calling the function with a value of whatToPrint.append(mylist[i]). However, list.append() does not return anything, it appends to the list in-place; so you're passing None to the function on all recursive calls. You should append to the list then pass the list in as a parameter. More on reddit.com
🌐 r/learnpython
15
3
May 11, 2024
pycharm - How to specify that a parameter is a list of specific objects in Python docstrings - Stack Overflow
In essence, to declare a list return type using type-hinting (Python >=3.5), you may do something like this: from typing import List """ Great foo function. More on stackoverflow.com
🌐 stackoverflow.com
Force argument type in a function
You can also use things like mypy which is a static type checker. def my_function(arg1: str) -> str: return f'Your string was : {arg1}' More on reddit.com
🌐 r/learnpython
7
3
January 23, 2021
🌐
W3Schools
w3schools.com › python › gloss_python_function_passing_list.asp
Python Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches ...
🌐
Mypy
mypy.readthedocs.io › en › stable › cheat_sheet_py3.html
Type hints cheat sheet - mypy 2.3.1 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 something-else-like) is called a “duck type”, and several duck types that are common in idiomatic Python are standardized.
🌐
TecAdmin
tecadmin.net › python-function-with-parameters-return-and-data-types
Python Function with Parameters, Return and Data Types – TecAdmin
April 26, 2025 - However, as of Python 3.5, you can use type hints to indicate the expected data types of function parameters and the return value. This doesn’t enforce the data types, but it can make your code easier to understand. Here’s an example: In this function, the numbers parameter is expected to be a list of integers, and the function is expected to return a tuple of two integers.
🌐
Medium
medium.com › @gauravverma.career › parameters-arguments-in-python-function-74a057662c0e
Parameters/Arguments in python function | by Gaurav Verma | Medium
December 7, 2025 - For more details, please refer “user defined functions in python” · ##Function without parameter and no return value def func_without_params_and_return_value(): print("this function does not have parameters") print("this function does not have return value") ##function with two parameter and no return value def my_function(firstname, lastname): print(firstname) print(lastname) ... While defining the function, we can pass the default value to parameter(s) of function in form of <parameter_name> = <default_value>
🌐
Built In
builtin.com › software-engineering-perspectives › arguments-in-python
5 Types of Python Function Arguments | Built In
Learn about the five different types of arguments used in python function definitions: default, keyword, positional, arbitrary positional and arbitrary keyword arguments. ... In Python, a function is defined with def.
Find elsewhere
🌐
The Python Coding Book
thepythoncodingbook.com › home › blog › using type hints when defining a python function [intermediate python functions series #6]
Using type hints when defining a Python function
March 19, 2023 - Type hints indicate that the data the function returns is a list of strings. Therefore the IDE “knows” that item should be a str in the final for loop since result is a list of strings.
🌐
Runestone Academy
runestone.academy › ns › books › published › thinkcspy › Lists › UsingListsasParameters.html
10.19. Using Lists as Parameters — How to Think like a Computer Scientist: Interactive Edition
For example, the function below takes a list as an argument and multiplies each element in the list by 2: The parameter aList and the variable things are aliases for the same object.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-functions
Python Functions - GeeksforGeeks
Python supports different types of arguments that can be passed during a function call. 1. Default argument: Default argument use a predefined value when no value is passed during the function call. ... Since y is not provided, it uses the default value 50. 2. Keyword Arguments: pass values using parameter ...
Published: 2 weeks ago
🌐
PYnative
pynative.com › home › python › basics › python function arguments
Python Function Arguments [4 Types] – PYnative
August 2, 2022 - Learn different types of arguments used in the python function with examples. Learn Default, Keyword, Positional, and variable-length arguments
🌐
Medium
ishanjainoffical.medium.com › python-function-type-of-arguments-in-a-function-e613e483fa00
Python Function: Type of Arguments in a Function | by Data Science & Beyond | Medium
October 1, 2023 - We define a function called make_pizza with four parameters: topping1, topping2, topping3, and cheese. Inside the function, we print out the toppings and the type of cheese. When we call the make_pizza function without specifying the cheese (i.e., make_pizza()), Python uses the default value of "mozzarella" for the cheese because we told it to do so in the function definition.
🌐
Python.org
discuss.python.org › documentation
Explicit parameter list in function documentation - Documentation - Discussions on Python.org
May 31, 2022 - I prefer the parameters of a function (with their documentation) to be listed explicitly in the function’s documentation. This is in contrast with man-style, which describes the positionals in prose. Compare open (what I call man-style) with numpy.linalg.norm (what I say employs an explicit list).
🌐
Reddit
reddit.com › r/learnpython › why isn´t the parameter of the function of type list?
r/learnpython on Reddit: Why isn´t the parameter of the function of type list?
May 11, 2024 -

When I run the following code, I get an error the error: noneType object has no attribute 'append'

Why is this? I am handing in an empty list. How is this different from mylist = [], which works as expected.

(Damn, do I miss C already.)

def func(mylist, whatToPrint):
  if len(mylist) == 1:
    whatToPrint.append(list[0])
    print(whatToPrint)
    return 0
  for i in range(len(mylist)):
    tmp = mylist.copy()
    tmp.pop(i)
    func(tmp, whatToPrint.append(mylist[i]))
    return 0

mylist = []

while True:
  mylist.append(input())
  if input("Last input? (Y/N)") == "Y":
    break

func(mylist, [])

input("Close program with any key.")
🌐
Python
peps.python.org › pep-0695
PEP 695 – Type Parameter Syntax | peps.python.org
It also modifies existing AST node types FunctionDef, AsyncFunctionDef and ClassDef to include an additional optional attribute called typeparams that includes a list of type parameters associated with the function or class.
🌐
LogRocket
blog.logrocket.com › home › understanding type annotation in python
Understanding type annotation in Python - LogRocket Blog
June 4, 2024 - As you can see, we can call the function with a tuple or list and the function works properly. We don’t have to limit parameters to list if all the function does is get an item. For Python ≤3.8, you need to import Sequence from the typing module: ... The dict type specifies that the person dictionary keys are of type str and values are of type str.
🌐
GitConnected
levelup.gitconnected.com › 5-types-of-arguments-in-python-function-definition-e0e2a2cafd29
5 Types of Arguments in Python Function Definitions | by Indhumathy Chelliah | Level Up Coding
April 14, 2022 - The function definition starts with the keyword def. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented. — python docs
🌐
DataFlair
data-flair.training › blogs › python-function-arguments
Python Function Arguments with Types, Syntax and Examples - DataFlair
April 14, 2026 - Previously, we have covered Functions in Python. In this Python Function Arguments tutorial, we will learn about what function arguments are used in Python and their types: Python Keyword Arguments, Default Arguments in Python, and Python Arbitrary Arguments.