Python Forum
Sum of Numbers in a List - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sum of Numbers in a List (/thread-15523.html)



Sum of Numbers in a List - MrGoat - Jan-20-2019

So this was the question description :
# Write a Python function to sum all the numbers in a list.
# Sample List : (8, 2, 3, 0, 7)
# Expected Output : 20

This is my code :

lst = []
i = 0
sum = 0

print ("Enter how many numbers:")
x = input()
while i < int(x):
    print ("Enter number: ")
    y = input()
    lst.append(y)
    i = i + 1

def sum():
    for i in range(x-1):
        sum = lst[i] + sum
        i = i + 1
        print ("sum")
When I tried to run the code in my terminal, I got the prompt to enter how many numbers there were in the list and also the prompt to enter the individual numbers. However, the code ends there immediately ... it doesn't print out the sum of the numbers. What am I missing, please advise thanks alot !


RE: Sum of Numbers in a List - Larz60+ - Jan-20-2019

are you required to write the sum function? there is a bulit-in one
>>> xx = [1,2,3,4,5,6]
>>> sum(xx)
21



RE: Sum of Numbers in a List - MrGoat - Jan-20-2019

(Jan-20-2019, 01:19 PM)Larz60+ Wrote: are you required to write the sum function? there is a bulit-in one
>>> xx = [1,2,3,4,5,6]
>>> sum(xx)
21

I wanted to do it without using the built-in function for practice


RE: Sum of Numbers in a List - perfringo - Jan-20-2019

Some observations:

- sum() is Python built-in function. Never use it as name.

- I personally prefer take user input in following way (subjectively it's more readable): x = int(input("Enter how many numbers: ))

- otherwise your code a quite a mess; you set sum to zero then create function with same name. You use name sum inside of function sum; function is defined but never used etc.

Function should be quite simple: you have list, you define total with value zero, you iterate over list elements and add all elements to total, you return total.


RE: Sum of Numbers in a List - snippsat - Jan-20-2019

(Jan-20-2019, 01:40 PM)MrGoat Wrote: I wanted to do it without using the built-in function for practice
Can do it like this.
>>> tup = (8, 2, 3, 0, 7)
>>> total = 0
>>> for n in tup:
...     total += n
...     
>>> total
20



RE: Sum of Numbers in a List - perfringo - Jan-20-2019

If you want to practice even more then you could enter wonderful world of recursion.

One way of sum list elements:

>>> def sum_of_list_elements(lst):
...     if not lst:                       
...         return 0
...     else:
...         return lst[0] + sum_of_list_elements(lst[1:])



RE: Sum of Numbers in a List - MrGoat - Jan-20-2019

(Jan-20-2019, 02:29 PM)perfringo Wrote: If you want to practice even more then you could enter wonderful world of recursion.

One way of sum list elements:

>>> def sum_of_list_elements(lst):
...     if not lst:                       
...         return 0
...     else:
...         return lst[0] + sum_of_list_elements(lst[1:])

How come the parameter of function can be a list? --> 1st line of your code


RE: Sum of Numbers in a List - perfringo - Jan-20-2019

(Jan-20-2019, 02:37 PM)MrGoat Wrote: How come the parameter of function can be a list? --> 1st line of your code

Why can't function be defined with list as parameter and given argument as list if used?

This function can handle tuples as well, with converting also dictionaries:

>>> sum_of_list_elements((8, 2, 3, 0, 7))
20
>>> sum_of_list_elements([8, 2, 3, 0, 7])
20
>>> sum_of_list_elements(list({1: 10, 2: 20}))                # sum of dict keys
3
>>> sum_of_list_elements(list({1: 10, 2: 20}.values()))       # sum of dict values
30

In real-life scenarios always use built-in function sum() as Larz60+ suggested.

However, if you are in process of learning and expanding your knowledge it is useful to play with different code snippets. For example, if you are in process of learning recursion and algorithms at the same time you can combine them into function which sums list elements. Combining "divide and conquer" with recursion enables us to express list elements sum function as follows:

def sum_of_list_elements(lst):
    if not lst:
        return 0
    elif len(lst) == 1:
        return lst[0]
    else:
        middle = len(lst) // 2
        return sum_of_list_elements(lst[:middle]) + sum_of_list_elements(lst[middle:])



RE: Sum of Numbers in a List - aakashjha001 - Jan-27-2019

#Working code
lst = []
i = 0


print("Enter how many numbers:")
x = input()
while i < int(x):
    print("Enter number: ")
    y = input()
    lst.append(int(y))
    i = i + 1


def sum1():
    sum=0
    for z in range(0,int(x)):
        sum =lst[z] + sum

    print(sum)
sum1()