OneBite.Dev - Coding blog in a bite size

find the sum of all elements in an array in python

Code snippet on how to find the sum of all elements in an array in python

total = 0
for num in array_name:
  total = total + num
print(total)

This code uses a for loop to iterate over the given array and tally the sum of all its elements. Firstly, it initiates the total value to 0 (this will be the final sum of all elements). Then, it creates a loop that iterates over each element in the given array. The loop adds the value of each element to the total variable and stores it. Finally, the loop prints the value of the total variable, which is the sum of all elements in the array.

python