DEV Community

Avnish
Avnish

Posted on

Python Program to Find the Sum of an Array

Finding the sum of an array is a fundamental operation in programming. Python provides multiple ways to achieve this, ranging from simple loops to built-in functions and advanced techniques like recursion and functional programming. This article explores different methods to compute the sum of an array in Python.

Example

Consider an array:

arr = [5, 8, 12, 20]
Enter fullscreen mode Exit fullscreen mode

The sum of the elements is:

5 + 8 + 12 + 20 = 45
Enter fullscreen mode Exit fullscreen mode

We will explore various approaches to compute this sum.


1. Using a Loop (Iterative Method)

The simplest way to find the sum of an array is to iterate through its elements and accumulate their sum.

# Function to calculate sum using a loop
def sum_array(arr):
    total = 0
    for num in arr:
        total += num
    return total

# Example usage
arr = [5, 8, 12, 20]
print("Sum of the array is", sum_array(arr))
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(1)


2. Using Python’s Built-in sum() Function

Python provides an inbuilt function sum() that directly computes the sum of an iterable.

arr = [5, 8, 12, 20]
print("Sum of the array is", sum(arr))
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(1)


3. Using the reduce() Function

The reduce() function from the functools module applies a function cumulatively to the elements of an iterable.

from functools import reduce

arr = [5, 8, 12, 20]
result = reduce(lambda x, y: x + y, arr)
print("Sum of the array is", result)
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(1)


4. Using Recursion

A recursive function can be used to compute the sum by breaking down the array into smaller parts.

def recursive_sum(arr, n):
    if n == 0:
        return 0
    return arr[n - 1] + recursive_sum(arr, n - 1)

arr = [5, 8, 12, 20]
print("Sum of the array is", recursive_sum(arr, len(arr)))
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(n) (due to recursive call stack)


5. Using enumerate()

The enumerate() function helps iterate over the array while keeping track of indices.

arr = [5, 8, 12, 20]
sum_value = sum(a for i, a in enumerate(arr))
print("Sum of the array is", sum_value)
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(1)


6. Using Divide and Conquer (Recursive Approach)

This approach splits the array into halves, computes the sum of each half recursively, and combines the results.

def sum_of_array(arr, low, high):
    if low == high:
        return arr[low]
    mid = (low + high) // 2
    left_sum = sum_of_array(arr, low, mid)
    right_sum = sum_of_array(arr, mid + 1, high)
    return left_sum + right_sum

arr = [5, 8, 12, 20]
print("Sum of the array is", sum_of_array(arr, 0, len(arr)-1))
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(log n) (due to recursive call stack)


7. Using the Counter Method

The Counter class from collections helps count occurrences of elements and calculate the sum efficiently.

from collections import Counter

arr = [5, 8, 12, 20]
c = Counter(arr)
result = sum(k * v for k, v in c.items())
print("Sum of the array is", result)
Enter fullscreen mode Exit fullscreen mode

Output:

Sum of the array is 45
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Auxiliary Space: O(n) (due to Counter storage)


Conclusion

This article explored multiple ways to find the sum of an array in Python. The best method depends on the use case:

  • For simplicity: Use sum(arr)
  • For functional programming: Use reduce()
  • For recursion-based solutions: Use recursive_sum() or Divide and Conquer
  • For advanced counting: Use Counter

Each method provides a unique perspective on solving this common problem efficiently.

Top comments (0)