Change language

Python program to find the sum of items in a list

|

Example :

  Input:  [12, 15, 3, 10]  Output:  40  Input:  [17, 5, 3, 5]  Output:  33 

Example # 1:

< / code>

Exit :

 Sum of all elements in given list: 74 

Example # 2. Using a while () loop

# Python program for finding the sum of items in a list

total = 0

  
# create a list

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

  
# Iterate each item in the list
# and add them in total

for ele in range ( 0 , len (list1)):

  total = total + list1 [ele]

  
# print total cost

print ( "Sum of all elements in given list:" , total)

# Python program for finding the sum of items in a list

total = 0

ele = 0

  
# create a list

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

 
# Iterate each item in the list
# and add them in total

while (ele & lt;  len (list1)):

total = total + list1 [ele]

ele + = 1

 
# print total cost

print ( "Sum of all elements in given list:" , total)

Output:

 Sum of all elements in given list: 74 

Example # 3: recursive way

< td class = "code">

# Python program to find the sum of all
# items in the list using recursion

 
# create a list

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

 
# creating the sum_list function

def sumOfList ( list , size):

if (size = = 0 ):

return 0

else :

  return list [size - 1 ] + sumOfList ( list , size - 1 )

 
# Driver code

total =   sumOfList (list1, len (list1))

 

print ( "Sum of all elements in given list:" , total)

Exit :

 Sum of all elements in a given list: 74 

Example # 4: Using the

# Python program for finding the sum of items in a list

  
# create a list

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

 
# using the sum () function

total = sum (list1)

 
# print total cost

print ( "Sum of all elements in given list:" , total)

Exit:

 Sum of all elements in given list: 74 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method