简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM