Sum all Items in Python List without using sum()
Last Updated :
26 Feb, 2024
In Python, summing all the elements of a list is a common task, and while the `sum()` function simplifies the process, you can also implement the summation manually using a loop. By iterating through each element in the list and accumulating the total, you can achieve the same result without relying on the built-in `sum()` function. This alternative approach allows you to gain a deeper understanding of the underlying mechanics of list manipulation in Python.
Sum All The Items In Python List Without Using Sum()
Below, are the methods to Sum All The Items In the Python List Without Using Sum() in Python
Sum All The Items In Python List Using For Loop
In this method we use for loop which iterates through each element in the list, adding it to a running total. It’s one of the simple approaches that returns the sum of all items sequentially within the list.
Python
mylist = [ 10 , 20 , 30 , 40 , 50 ]
total_sum = 0
for item in mylist:
total_sum + = item
print (total_sum)
|
Sum All The Items In Python List Using While Loop
Using this method, we can calculate sum of all elements of a list iteratively without the need for recursion or higher-order functions. The loop continues until the index reaches the length of the list, adding each element to the total sum. And when loop terminates, we get the final sum.
Python3
my_list = [ 10 , 20 , 30 , 40 , 50 ]
total_sum = 0
index = 0
while index < len (my_list):
total_sum = total_sum + my_list[index]
index + = 1
print (total_sum)
|
Sum All The Items In Python List Using Recursion
In this method, recursion is employed to recursively sum up the elements of the list. The base case checks if the list is empty, returning 0 if true. Otherwise, it adds the first element of the list to the result of recursively calling the function on the rest of the list.
Python
my_list = [ 10 , 20 , 30 , 40 , 50 ]
def find_sum(lst):
if len (lst) = = 0 :
return 0
else :
return lst[ 0 ] + find_sum(lst[ 1 :])
total_sum = find_sum(my_list)
print (total_sum)
|
Conclusion
Conclusion: While the built-in sum()
function is the most concise way to sum all items in a Python list, exploring alternative methods using a for loop, recursion, and a while loop can enhance your understanding of different programming techniques. Each approach has its strengths and weaknesses, and choosing the right one depends on the specific requirements of your program.
Share your thoughts in the comments
Please Login to comment...