Python – Non-recursive sum function for lists

Send Us a Sign! (Contact Us!)

The following custom sum() function is non-recursive solution (it will return in a single instance a single integer as output) to sum all integer elements of a list:

def sum(listNum):
    if len(listNum) == 1: 
        print (listNum[0], 'contains only 1 element.')
        return listNum[0]
        theSum = 0
        for i in listNum:
            theSum = theSum + i
            return theSum

Note that this function needs only a parameter (list type) and it will check even if there is only 1 element in list, in which case it will return his value.

1 thought on “Python – Non-recursive sum function for lists”

Comments are closed.