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.

  1. User Input for Array Size

    • The user enters the number of elements they want in the array.
  2. Array Input

    • A loop runs size times, taking user input and storing it in number_array.
  3. Summation Using sum()

    • The sum() function is used to compute the total sum of all elements in number_array.
  4. 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