-1

I was using a website called LeetCode trying to write a piece of code for this:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

I eventually wrote this code that someone told me about:

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        output = []
        sum = 0
        for i in nums:
            sum += i
            output.append(sum)
        return output

One thing I am confused about is this:

List[]

What exactly is this?

  • 1
    That's a very broad set of answers that covers the topic. `-> List[int]` is saying that the function returns a list of integers. – Carcigenicate May 02 '21 at 14:08

1 Answers1

0

You can use this documentation or this article:

Python supports static typing so you can use it like this:

from typing import List

#for variable
var1: int = 22

#for function(arg1: arg1_type, arg2: arg2_type) -> function_return_type
def func1(arg1: int, arg2:str) -> float:
    pass

#for a list that its values are int, float, etc.
var2: List[int] = [2, 4, 9]

So you will tell the python interpreter that my var2 is a list and its children are integer.


Update: Thank you JonSG for your comment. Yes, type-hints are ignored by the python interpreter in the runtime so we should use some tools as type-checkers. I recommend Static Typing in Python to learn more about python type-hints and the type-checkers we can use.

  • Type hints are ignored by the runtime. At the moment, to get anything out of them other than documentation you use would need an editor/tool/plugin that does the checking at design time. – JonSG May 02 '21 at 15:30