6

I am new to Python and need some help writing a function that takes a list as an argument.

I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.

My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:

  def sum(list):

It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.

Thanks in anticipation!

EDIT: I am looking for something like this (thanks, "irrenhaus"):

def listsum(list):
    ret=0
    for i in list:
        ret += i
    return ret

# The test case:
print listsum([2,3,4])  # Should output 9.
Bart Riordan
  • 436
  • 3
  • 8
  • 23
Blnpwr
  • 1,793
  • 4
  • 22
  • 43
  • 1
    How do you store the user input? Could you post some code of what you have already tried? – llrs Apr 25 '14 at 15:11
  • 1
    I understand you are a beginner which is fine. I'm unclear on what you mean by "the interpreter wants a list". Can you detail what you did? Did you learn yet how to write a loop? – usr Apr 25 '14 at 15:11
  • possible duplicate of [Test if a variable is a list or tuple](http://stackoverflow.com/questions/2184955/test-if-a-variable-is-a-list-or-tuple) – La-comadreja Apr 25 '14 at 15:13
  • 1
    also, you shouldn't name something after a built-in, namely "list" – acushner Apr 25 '14 at 15:14
  • I want something like this: " User enters a list of Int's , such as [1,2,3,4,5] , my for loop sums the elements in the list and returns 15. " Hope this a bit clearer. – Blnpwr Apr 25 '14 at 15:14
  • `list.append()` does not return. It modifies the list in place. That may be your problem. If you had `list = list.append()`, you'll find `list` to be `None`. –  Apr 25 '14 at 15:15
  • @user2938633 And what did you tried? The list will have always consecutive numbers? – llrs Apr 25 '14 at 15:15
  • I failed to try this because I do not know how to build a function that takes a list as input. – Blnpwr Apr 25 '14 at 15:16
  • 1
    `[float(i) for i in raw_input('lists of numbers').rstrip(']').lstrip('[').split(',')]` for a quick and hackery solution. –  Apr 25 '14 at 15:16
  • 2
    Show us all the code you tried, not just your definition of sum. In particular, show us your input code and surrounding code. –  Apr 25 '14 at 15:16
  • @user2938633 But how do you take this input? Is it python 2.x or 3.x? – llrs Apr 25 '14 at 15:17

11 Answers11

4

I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.

Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.

# ASSUMING PYTHON3

user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number

def sum(lst):
    accumulator = 0
    for element in lst:
        accumulator += element
    return accumulator

The top three lines are kind of ugly. You can combine them:

user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))

But that's kind of ugly too. How about:

raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
    processed_in = map(float, raw_in)
    # if you specifically need this as a list, you'll have to do `list(map(...))`
    # but map objects are iterable so...
except ValueError:
    # not all values were numbers, so handle it
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Thank you very much but this a bit too much for me. Please look at my edited question to see what I am looking for. – Blnpwr Apr 25 '14 at 15:27
  • @user2938633 the answer you're looking for SPECIFICALLY REQUIRES us to know what your input looks like. You seem to gloss over that requirement in every comment that asks for it, so I'm assuming you already know how to get the user's input. If so, TELL US EXACTLY WHAT THE USER INPUTS. Don't say they input `[1,2,3]`, tell us they input `"1, 2, 3"` and you split on commas, or they input `"[1,2,3]"` and you parse out the brackets and the commas, or etc etc. – Adam Smith Apr 25 '14 at 15:37
1

The for loop in Python is exceptionally easy to use. For your application, something like this works:

def listsum(list):
    ret=0
    for i in list:
        ret+=i
    return ret

# the test case:
print listsum([2,3,4])
# will then output 9

Edit: Aye, I am slow. The other answer is probably way more helpful. ;)

irrenhaus3
  • 126
  • 1
  • 4
1

This will work for python 3.x, It is similar to the Adam Smith solution

list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
    try:
        value = int(value) #Check if it is number
    except:
        continue
    total += value

print(total)
llrs
  • 3,308
  • 35
  • 68
0

You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]

    def my_sum(args):
    sum = 0
    for arg in args:
        if isinstance(arg, (list, tuple)):
            sum += my_sum(arg)
        elif isinstance(arg, int):
            sum += arg
        else:
            raise TypeError("unsupported object of type: {}".format(type(arg)))
    return sum

for my_sum([1, 2, [1, 2, [1, 2]]]) the output will be 9.

If you used standard buildin function sum for this task it would raise an TypeError.

Przemek
  • 647
  • 2
  • 8
  • 25
0

This is a somewhat slow version but it works wonders

# option 1
    def sumP(x):
        total = 0
        for i in range(0,len(x)):
            total = total + x[i]
        return(total)    

# option 2
def listsum(numList):
   if len(numList) == 1:
        return numList[0]
   else:
        return numList[0] + listsum(numList[1:])

sumP([2,3,4]),listsum([2,3,4])
Rafael Díaz
  • 2,134
  • 2
  • 16
  • 32
0

This should work nicely

user_input =  input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")

print ("The list of numbers entered by user:" user_list)


ds = 0
for i in user_list:
    ds += int(i)
print("sum = ", ds)

}

0

Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:

def sumTo(n):
runTotal=0
for i in range(n+1):
    runTotal=runTotal+i
return runTotal

print sumTo(15) #outputs 120

debiday
  • 47
  • 7
0

If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce

from functools import reduce
from operator import add

def sumList(list):
     return reduce(add, list)
Bharathiraja
  • 714
  • 1
  • 12
  • 20
0
def oper_all(arr, oper):
    sumlist=0
    for x in arr:
        sumlist+=x
    return sumlist
Flair
  • 2,609
  • 1
  • 29
  • 41
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 15 '21 at 15:32
  • 2
    When the `oper` argument? You don't make use of it. – joanis Dec 15 '21 at 22:42
-1

Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"

def addelements(l):
    if all(isinstance(item,int) for item in l) and isinstance(l,list):
        add=0
        for j in l:
            add+=j
        return add
    return 'Not a list or list does not have all the integer elements'

if __name__=="__main__":
    l=[i for i in range(1,10)]
#     l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
    print addelements(l)

Output:

45
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • Why did you do `isinstance` in your first version but `type ==` in this version? I'm confused. – Adam Smith Apr 25 '14 at 15:19
  • @AdamSmith Here in first condition i am checking that every element in list is int and inputted list is instance of list. – Nishant Nawarkhede Apr 25 '14 at 15:21
  • [`isinstance`](http://stackoverflow.com/q/1549801/2886003) is the way to check this – llrs Apr 25 '14 at 15:26
  • @Llopis Can you please explore it more bit. Thnaks – Nishant Nawarkhede Apr 25 '14 at 15:28
  • @Fledgling you used `isinstance` in that SAME LINE. Just use it to check that `item` is an `int` as well :P. I edited for you since you asked me to. – Adam Smith Apr 25 '14 at 15:29
  • @Fledgling I expirence that in [this question](http://stackoverflow.com/q/22687656/2886003) Basically is the function to do it avoiding some unexpected results. Look the documentation also, if you have more doubts, and the linked question of my previous comment is also clear about it. – llrs Apr 25 '14 at 15:34
  • This answer would be better if it provided some explanation in addition to the code. – Thom Apr 25 '14 at 15:44
-1
import math



#get your imput and evalute for non numbers

test = (1,2,3,4)

print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why? 
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)] 
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33
mgg07
  • 1
  • Welcome to SO. This does not really answer the original question. The OP is trying to write their own implementation of `sum()` ... not know how many different versions of it already exist. – kdopen Feb 06 '15 at 00:58
  • This doesn't have anything to do with writing a version of the `sum` function. – EvergreenTree Feb 06 '15 at 00:58