Python program to find the sum of all elements of an array

Find the sum of the array in Python: Here, we are going to learn how to find the sum of all elements of an array using the python program? By IncludeHelp Last updated : January 14, 2024

Problem statement

Given an integer array and we have to find the sum of all elements in Python.

Find the sum of array elements

There are two ways to find the sum of all array elements, 1) traverse/access each element and add the elements in a variable sum, and finally, print the sum. And, 2) find the sum of array elements using sum() function.

Example

Consider the below example with sample input and output:

Input: 
arr = [10, 20, 30, 40, 50]

Output:
sum = 150

Approach 1: Traverse elements and add them

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

Approach 2: Using the sum() method

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

Python program for sum of the array elements

# Python program for sum of the array elements

# functions to find sum of elements

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

# main function
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    print ('sum_1: {}'.format(sum_1(arr)))
    print ('sum_2: {}'.format(sum_2(arr)))

Output

sum_1: 150
sum_2: 150

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.