Python Tutorial (33) – Example: Calculating the sum of array elements

Time: Column:Python views:215

Define an Integer Array and Calculate the Sum of its Elements

The following Python code demonstrates how to define an integer array and calculate the sum of its elements using the built-in sum() function.

Requirement:

  • Input: arr[] = {1, 2, 3}

  • Output: 6

  • Calculation: 1+2+3=61 + 2 + 3 = 6

Example:

# Define a function to calculate the sum of an array, arr is the array, n is its length (not used here)
def _sum(arr, n):
    # Using the built-in sum function to calculate the total
    return sum(arr)

# Initialize the array
arr = [12, 3, 4, 15]

# Calculate the length of the array
n = len(arr)

# Call the sum function and store the result
ans = _sum(arr, n)

# Output the result
print('The sum of array elements is', ans)

Output:

The sum of array elements is 34

In this code, the function _sum(arr, n) calculates the sum of all elements in the array. For the array [12, 3, 4, 15], the sum is 34.