Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Summing Array Elements

Python Summing Array Elements

Document Object Reference Manual Python3 Examples

Define an integer array and calculate the sum of its elements.

Requirements:

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

Output : 6

Calculation: 1 + 2 + 3 = 6

Example

Define a function where arr is the array and n is the array length, which can be used as a spare parameter; it is not used here

def

_sum

(

arr

,

n

)

:

     

   

Calculate using the built-in sum function

   

return

(

sum

(

arr

)

)

 

Calling a function

arr

=

[

]

Array elements

arr

=

[

12

,

3

,

4

,

15

]

 

Calculate the length of the array elements

n

=

len

(

arr

)

 

ans

=

_sum

(

arr

,

n

)

 

Output result

print

(

'The sum of the array elements is'

,

ans

)

The output of the above example is:


数组元素之和为 34

Document Object Reference Manual Python3 Examples