1 min read
Make a Python Function which takes an array or list as input and returns the sum of its elements, for example array[ 1, 2, 3, 4] will return 1 + 2 + 3 + 4 = 10
In this article, we will go through two different methods of tackling the same problem.
In this method first, we are creating a variable
total to store the sum and initializing it to 0. Next, the for loop iterates over each element of the array / list and storing their sum in the total variable, at last function returns the total.
def array_summer(arr): total = 0 for item in arr: # shorthand of total = total + item total += item return total # Test input print(array_summer([1, 2, 3, 3, 7]))
Python comes with an in-built solution for adding items of iterable (list, tuple, dictionary), the
sum() method simply returns the sum of each item of the gives list or array.
def array_summer(arr): return sum(arr) # Test input print(array_summer([1, 2, 3, 3, 7]))
we went through two different methods of summing the elements of an array however using
sum() function made our code more compact and faster, for a very large list
sum() is more efficient therefore it's the recommended way.
Latest from djangocentral