How to Sum All the Items in Python List Without using sum()
Published on Aug. 22, 2023, 12:16 p.m.
To sum all the items in a Python list without using the built-in sum()
function, you can use a loop to iterate through the list and add up the values. Here is an example code:
my_list = [1, 2, 3, 4, 5]
sum = 0
for num in my_list:
sum += num
print("The sum of all the elements in the list is:", sum)
In this code, we first define a list called my_list
containing some integers. We then initialize a variable called sum
to 0. We use a for loop to iterate through each element in the list, adding it to the sum
variable using the +=
operator. Finally, we print out the total sum of all the elements in the list.
This approach is simple and easy to understand. However, if you have a very large list with many elements, using the built-in sum()
function is generally faster and more efficient.
To sum all the items in a Python list using the sum()
built-in function
To sum all the items in a Python list using the sum()
built-in function, you can simply pass the list as an argument to the sum()
function. Here is an example code:
my_list = [1, 2, 3, 4, 5]
total_sum = sum(my_list)
print("The sum of all the elements in the list is:", total_sum)
In this code, we first define a list called my_list
containing some integers. We then use the sum()
function to add up all the elements in the list and store the result in a variable called total_sum
. Finally, we print out the total sum of all the elements in the list.
Using the built-in sum()
function is generally faster and more efficient than using a loop to sum up all the elements in the list. However, if you want to avoid using the sum()
function for any reason, the loop-based alternative I provided earlier will do the job as well.