Search code examples
pythonpython-2.7built-in

In-built sum function in python


def sum_elements(l):
    sum = 0
    string = ""
    k = 0
    for i in l:
        if type(i) is int:
            sum = sum + l[k]
            k += 1
        elif type(i)is str:
            string = string + str(l[k])
            k += 1
    print "sum of integers in list" + str(sum)
    print "sum of strings in list" + string

Python has a built-in function sum to find sum of all elements of a list. In case the list is integer numbers sum_elements([1, 2, 3]), it will return 6. sum function works for a list of strings as well. sum_elements(["hello", "world"]) returns helloworld. I have written an implementation for the sum built-in function in the above code. It works.

I am a newbie in Python, I just want to know if it's correct or is there any better approach?

Are there are any links available for the python built-in functions source code?


Solution

  • You don't need to access an element by its index. If the list is not empty and all elements are of the same type, you can code as follows:

    >>> def sum_elements(l):
    ...     s = l[0]
    ...     for element in l[1:]:
    ...         s += element
    ...     return s
    ... 
    >>> sum_elements([1, 2, 3])
    6
    >>> sum_elements(['hello', 'world'])
    'helloworld'