41

What is the difference between using list and List when defining for example the argument of a function in python3? For example, what is the difference between

def do_something(vars: list):

and

def do_something(vars: List):

The documentation says:

class typing.List(list, MutableSequence[T])

Generic version of list. Useful for annotating return types.

but I'm not entirely sure what the above means.

I have similar questions for: dict vs Dict, set vs Set, etc.

1

1 Answer 1

28

Not all lists are the same from a typing perspective. The program

def f(some_list: list):
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])

won't fail a static type checker, even though it won't run. By contrast, you can specify the contents of the list using the abstract types from typing

def f(some_list: List[int]) -> List[int]:
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])

will fail, as it should.

Sign up to request clarification or add additional context in comments.

5 Comments

Note: PEP 585 changes this in Python 3.9. Lowercase list[int] works now.
@ScottJ So is list and List now completely the same?
@SearchSpace I'm not sure, but it seems capital List is no longer needed?
using list instead of List as typing annotation in python 3.8 and older will cause Typeerror: type object is not subscriptable
@ScottJ @SearchSpace Just read the docs. docs.python.org/3/library/typing.html#special-forms All the Types like List, Dict, etc (with a capital letter) were deprecated since Python 3.9 e.g. Deprecated since version 3.9: builtins.tuple now supports []. See PEP 585 and Generic Alias Type. You can use just list instead. The old types are left for backwards compatibility if you need to use them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.