Reputation: 151
I'm new to python programming. While solving a question on leetcode, I came across the below line of code.
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
It'd be very helpful if someone can explain why do we use Optional[ListNode]
?
**What does it do? How is it useful? **
Upvotes: 15
Views: 11121
Reputation: 11
Optional type is used to enable "None" values.
"Optional[X] is equivalent to X | None (or Union[X, None])."
Source: https://docs.python.org/3/library/typing.html
Upvotes: 1
Reputation: 21
It is to allow for values that can be None.
For example: These are all listnodes: (3 -> 1 -> None)
Example:
# Use Optional[] for values that could be None
x: Optional[str] = some_function()
Source: https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#
Upvotes: 2