1

I am starting out practicing python and came across this little code on leetcode:

def maxProfit(self, prices: List[int]) -> int:

Could someone please explain what the colon after prices does and what does List[int] and -> do?

I've just used a colon to slice lists/strings and denote the start of a code block indentation. Reading online I realized that prices : List[int] means that price is the argument name and the expression means that prices should be a list of integers and the return type of the function should be an integer.

Can someone tell me if this is correct or would like to expand on it?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    It doesn't do anything with the code. All it's used for is annotating what types the variables are supposed to be and what type the function should return. But it's not enforced in anyway, it's just a hint to the reader (and tools) – Ted Klein Bergman Dec 05 '20 at 17:52

2 Answers2

1

They are type annotations, List[int] refers to prices being a list of ints. While -> gives the type of the returning value, here maxProfit is supposed to return an int.

You are not required to use them.

Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 1
    Just to mark on words: It doesn't refer to `prices` *being* a list of ints. It suggest that the parameter should contain a list of ints, but there's no enforcement and could be anything. – Ted Klein Bergman Dec 05 '20 at 17:56
0

Those are called annotations or type hints. They basically tell the python interpreter of what type the input parameters should be and what is the function going to return.

So in

def maxProfit(self, prices: List[int]) -> int:

List[int] signifies that the function is expecting a list of integers as the input value of prices. But for it to actually work you have to import List from typing module.

Then -> int signifies that the functions return value is of type integer.

These will not make the code any better, but are helpful for autocomplete and profiling the code. If you are a beginner you don't have to worry about these just now.

Navaneeth Reddy
  • 315
  • 1
  • 12