-3

I have a lot of Matlab experience but trying to learn Python syntax from Leetcode challenges. What does the -> bool mean in the method below?

def isPalindrome(self, head: ListNode) -> bool:
    vals = []
    current_node = head
    while current_node is not None:
        vals.append(current_node.val)
        current_node = current_node.next
    return vals == vals[::-1]

Here's the entire code:

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def isPalindrome(self, head: ListNode) -> bool:
        vals = []
        current_node = head
        while current_node is not None:
            vals.append(current_node.val)
            current_node = current_node.next
        return vals == vals[::-1]
isPalindrome(head)

2 Answers2

1

The -> bool just tells that isPalindrome() returns a boolean, but it doesn't force the function to return a boolean.

Look at PEP 3107: https://www.python.org/dev/peps/pep-3107/

And PEP 484: https://www.python.org/dev/peps/pep-0484/ It states:

Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

This is called function annotation.

You could also use mypy to do type checking on your code.

Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or “duck”) typing and static typing.

krmogi
  • 2,588
  • 1
  • 10
  • 26
1

It is called a type hint. Basically, it gives you hints as to what type the function will return.

In your code, -> bool hints that isPalindrome() returns a boolean value.

Akash
  • 17
  • 6