Python Program to find sum of array elements using sum function
Program
number_array = list()
size = int(input("Enter the size of array:\t"))
print("Enter the numbers in array: ")
for i in range(int(size)):
n = input()
number_array.append(int(n))
total = sum(int(i) for i in number_array)
print("Sum of array is:\t", total)
This program calculates the sum of all elements in an array using Python’s built-in sum()
function.
-
User Input for Array Size
- The user enters the number of elements they want in the array.
-
Array Input
- A loop runs
size
times, taking user input and storing it innumber_array
.
- A loop runs
-
Summation Using
sum()
- The
sum()
function is used to compute the total sum of all elements innumber_array
.
- The
-
Display the Sum
- The final sum of all array elements is printed.
Key Takeaways
- Uses Python’s built-in
sum()
function, making the code shorter and more efficient. - Reads numbers into an array and directly calculates the sum using
sum(int(i) for i in number_array)
. - Eliminates the need for an explicit loop for summation.
Output
$ python3 sum_of_array_elements.py
Enter the size of array: 6
Enter the numbers in array:
1
3
5
6
8
0
Sum of array is: 23