Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to find the sum of array
In this article, we will learn different approaches to find the sum of all elements in an array. Python provides both manual iteration and built-in functions to accomplish this task.
Problem Statement
Given an array as input, we need to compute the sum of all elements in the array. We can solve this using manual iteration or Python's built-in sum() function.
Method 1: Using Built-in sum() Function
The simplest approach uses Python's built-in sum() function ?
# Using built-in sum() function
arr = [1, 2, 3, 4, 5]
result = sum(arr)
print('Sum of the array is', result)
Sum of the array is 15
Method 2: Using Manual Iteration
We can traverse the array and add each element to a sum variable ?
# Manual iteration approach
arr = [1, 2, 3, 4, 5]
total = 0
for element in arr:
total += element
print('Sum of the array is', total)
Sum of the array is 15
Method 3: Using While Loop
Alternative approach using a while loop with index ?
# Using while loop
arr = [1, 2, 3, 4, 5]
total = 0
i = 0
while i < len(arr):
total += arr[i]
i += 1
print('Sum of the array is', total)
Sum of the array is 15
Method 4: Using NumPy (For Large Arrays)
For numerical computations with large arrays, NumPy provides an efficient solution ?
import numpy as np
# Using NumPy
arr = np.array([1, 2, 3, 4, 5])
result = np.sum(arr)
print('Sum of the array is', result)
Sum of the array is 15
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
sum() |
O(n) | Simple arrays, readable code |
| Manual iteration | O(n) | Learning purposes, custom logic |
| While loop | O(n) | Index-based operations |
| NumPy | O(n) | Large arrays, numerical computing |
Conclusion
Python's built-in sum() function is the most efficient and readable approach for finding array sums. Use manual iteration when you need custom logic or are learning the fundamentals.
