Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use Optional[ListNode]?

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? **

like image 813
Samiksha Sharma Avatar asked Jan 18 '26 17:01

Samiksha Sharma


1 Answers

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#

like image 159
Imani-lvschkn Avatar answered Jan 21 '26 07:01

Imani-lvschkn