Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of Numbers in a List
#1
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 !
Reply
#2
are you required to write the sum function? there is a bulit-in one
>>> xx = [1,2,3,4,5,6]
>>> sum(xx)
21
Reply
#3
(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
Reply
#4
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(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
Reply
#6
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:])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(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
Reply
#8
(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:])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
#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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 15,636 Jan-05-2024, 08:30 PM
Last Post: sgrey
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,198 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  List of random numbers astral_travel 17 2,694 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,322 Nov-13-2022, 01:27 AM
Last Post: menator01
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,508 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Divide a number by numbers in a list. Wallen 7 8,019 Feb-12-2022, 01:51 PM
Last Post: deanhystad
  producing numbers out of a list bouraque7878 10 3,738 Nov-12-2021, 09:13 PM
Last Post: jefsummers
  How to change odd to even numbers in the list? plumberpy 8 3,716 Aug-08-2021, 11:07 AM
Last Post: plumberpy
  convert numbers into list lokesh 1 2,378 Jun-03-2021, 06:37 AM
Last Post: menator01
  adding numbers in a list Nickd12 2 2,190 Jan-15-2021, 12:46 PM
Last Post: Serafim

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020