Sum of list using while loop

def sum_list(lst: list) -> int:

"""Returns the sum of every other element in a list. Returns 0 if the

length of the list is less than 3"""

if len(lst) < 3:

return 0

total_sum: int = 0

index: int = 0

while index < len(lst):

total_sum += lst[index]

if index >= (len(lst) - 2):

break

index += 2

return total_sum

if __name__ == "__main__":

assert sum_list([1, 2]) == 0

assert sum_list([1, 2, 3]) == 4

assert sum_list([1, 2, 3, 4]) == 4

assert sum_list([1, 2, 3, 4, 5]) == 9

assert sum_list([1, 2, 3, 4, 5, 6]) == 9

/r/learnpython Thread