Python implements calculating the sum of list elements

王林
Release: 2020-05-10 11:35:39
Original
8843 people have browsed it

Python implements calculating the sum of list elements

Goal: Define a list of numbers and calculate the sum of the list elements.

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

Method 1:

total = 0
 
list1 = [11, 5, 17, 18, 23]  
 
for ele in range(0, len(list1)):
    total = total + list1[ele]
 
print("列表元素之和为: ", total)
Copy after login

Result:

列表元素之和为:  74
Copy after login
Copy after login
Copy after login

Method 2: Use while() loop

total = 0
ele = 0
 
list1 = [11, 5, 17, 18, 23]  
 
while(ele < len(list1)):
    total = total + list1[ele]
    ele += 1
     
print("列表元素之和为: ", total)
Copy after login

The output result of the above example is:

列表元素之和为:  74
Copy after login
Copy after login
Copy after login

Method 3: Use recursion

list1 = [11, 5, 17, 18, 23]

def sumOfList(list, size):
   if (size == 0):
     return 0
   else:
     return list[size - 1] + sumOfList(list, size - 1)
     
total = sumOfList(list1, len(list1))

print("列表元素之和为: ", total)
Copy after login

The result:

列表元素之和为:  74
Copy after login
Copy after login
Copy after login

Recommended tutorial: python tutorial

The above is the detailed content of Python implements calculating the sum of list elements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template