Valyrian
Valyrian

Reputation: 19

Summing the elements of an array

I wanted to sum all the elements of an array without using the sum() function. Here is what I did:

for i in range(0,len(student_heights)): 
    sum_heights+=student_heights[i] 

The right way was shown as:

for i in student_heights: sum_heights+=i

Is there a difference? Or was some other part of my code faulty?

Upvotes: 0

Views: 267

Answers (2)

Adon Bilivit
Adon Bilivit

Reputation: 27306

It may be helpful to show the performance benefits of enumerating the list versus indexing. I've also added use of sum() (although OP wants to avoid this) for comparison:

from random import random
from timeit import timeit

list_of_nums = [random() for _ in range(250)]

def func_1(list_):
    sum_ = 0
    for i in range(len(list_)):
        sum_ += list_[i]
    return sum_

def func_2(list_):
    sum_ = 0
    for v in list_:
        sum_ += v
    return sum_

def func_3(list_):
    return sum(list_)

for func in func_1, func_2, func_3:
    print(func.__name__, timeit(lambda: func(list_of_nums)))

Output:

func_1 9.773419732000093
func_2 5.5871382949999315
func_3 0.7234632429999692

Upvotes: 1

Sidharth Mudgil
Sidharth Mudgil

Reputation: 1461

There is no right way to sum list, Both methods have their advantage and disadvantages. like, In the first method we have access to the index and in the second method, we've direct access to the item.

You can sum all elements in the list using:

sum_heights = 0
for i in range(0,len(student_heights)): 
    sum_heights+=student_heights[i] 

or

sum_heights = 0
for i in student_heights: 
    sum_heights+=i

You can also use enumerate function, but it gives no benefit if you're only going to sum the list but in other problems, it can have many advatages

returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

for i, n in enumerate(student_heights): 
    sum_heights+=n

Upvotes: 0

Related Questions