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

Python Compute the Sum of List Elements

Python Compute the Sum of List Elements

Document Object Reference Manual Python3 Examples

Define a list of numbers and compute the sum of its elements.

For example: Input: [12, 15, 3, 10] Output: 40

Example 1

total

=

0

 

list1

=

[

11

,

5

,

17

,

18

,

23

]

 

 

for

ele

in

range

(

0

,

len

(

list1

)

)

:

    total

=

total + list1

[

ele

]

 

print

(

"The sum of the list elements is: "

,

total

)

The output of the above example is:


列表元素之和为:  74

Example 2: use a while() loop

total

=

0

ele

=

0

 

list1

=

[

11

,

5

,

17

,

18

,

23

]

 

 

while

(

ele

<

len

(

list1

)

)

:

    total

=

total + list1

[

ele

]

    ele +

=

1

     

print

(

"The sum of the list elements is: "

,

total

)

The output of the above example is:


列表元素之和为:  74

Example 3: use recursion

list1

=

[

11

,

5

,

17

,

18

,

23

]

def

sumOfList

(

list

,

size

)

:

   

if

(

size

==

0

)

:

     

return

0

   

else

:

     

return

list

[

size -

1

]

(

list

,

size -

1

)

     

total

=

sumOfList

(

list1

,

len

(

list1

)

)

print

(

"The sum of the list elements is: "

,

total

)

The output of the above example is:


列表元素之和为:  74

Document Object Reference Manual Python3 Examples