2
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?

2 Answers 2

4
from operator import add
def sum_elements(l):
    return reduce(add, l)
Sign up to request clarification or add additional context in comments.

1 Comment

NameError: name 'reduce' is not defined
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.