You can type a list as of Python 3.5
https://docs.python.org/3/library/typing.html
from typing import List
vector: List[float] = list()
or
from typing import List
vector: List[float] = []
Python is dynamically typed however https://www.python.org/dev/peps/pep-0484/
Typing makes it easier to read code, easier understand it, make efficient use of your IDE tooling and create higher quality software. I guess that's why it's in the PEP.
Answer from Shaun Ryan on Stack OverflowYou can type a list as of Python 3.5
https://docs.python.org/3/library/typing.html
from typing import List
vector: List[float] = list()
or
from typing import List
vector: List[float] = []
Python is dynamically typed however https://www.python.org/dev/peps/pep-0484/
Typing makes it easier to read code, easier understand it, make efficient use of your IDE tooling and create higher quality software. I guess that's why it's in the PEP.
Like Dominus said,
from typing import List is deprecated since Python 3.9.
You don't need to import anything, you can just use list.
Example:
my_list: list[float] = list()
Type Hints, can you indicate various types inside a list?
Checking the type of a list
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
Can someone explain why (type(meta[0]) == list) is False here?
list = [4,6,3] meta = [list] print(type(meta[0]) == list)
This prints False even though meta[0] is clearly a list. ChatGPT thinks this code should print True so at least I'm not the only one who's confused.