Calculating the Sum of Elements in a List
In this section, we will define a list of numbers and compute the sum of its elements.
Example
Input:
[12, 15, 3, 10]
Output:
40
Example 1: Using a Loop
total = 0 list1 = [11, 5, 17, 18, 23] for ele in range(0, len(list1)): total += list1[ele] print("Sum of list elements:", total)
Output:
Sum of list elements: 74
In this example, we use a for
loop to iterate through the list and sum its elements.
Example 2: Using a while
Loop
total = 0 ele = 0 list1 = [11, 5, 17, 18, 23] while(ele < len(list1)): total += list1[ele] ele += 1 print("Sum of list elements:", total)
Output:
Sum of list elements: 74
In this example, we use a while
loop to calculate the sum of the list elements.
Example 3: Using Recursion
list1 = [11, 5, 17, 18, 23] def sumOfList(lst, size): if size == 0: return 0 else: return lst[size - 1] + sumOfList(lst, size - 1) total = sumOfList(list1, len(list1)) print("Sum of list elements:", total)
Output:
Sum of list elements: 74
In this example, we use a recursive function to compute the sum of the list elements.