0

I want to write the function below in a more concise manner:

def sum_list(l):
    x = 0
    for i in l:
        x += i
    return x

I know I could easily do this:

def sum_list(l):
    return sum(l)

But I have been tinkering with generators and list comprehension in an effort to better understand python.

So I tried:

def sum_list(l):
    x = 0
    return (x += i for i in l)

But this just returns the generator object. I remember reading somewhere that it should be used within an operation like sum() or something along those line but I cannot seem to find that article anymore.

Can someone kindly point me in the direction of some literature that covers this, or possibly take the time to explain some of the basics surrounding statements of this nature?

1
  • 2
    return (x += i for i in l) this thing doesn't works in python, python doesn't allows assignments inside comprehension or generators. Commented May 2, 2012 at 4:46

1 Answer 1

5

I think you want reduce - http://docs.python.org/library/functions.html#reduce

def sum_iterable(a):
    return reduce(lambda x,y: x+y, a, 0)

Basically, reduce lets you 'fold' an iterable or list into a value. You wouldn't want a generator expression for something that should return a single value.

Sign up to request clarification or add additional context in comments.

6 Comments

I will vote this up if you don't shadow the built in sum() function, and add the proper return statement
Well this was the way we did it before sum() existed
in other languages, this would be easier to write, because operator.plus would be in the default namespace
Thanks! Would you happen to know of any good resources to get better acquainted with generator basics. For example, I just found out that enclosing with brackets creates a list, as opposed to parenths which creates a generator object...
@Verbal_Kint, start with this stackoverflow question. IMO one of the best resources on python generators is dabeaz.com/generators (written by David Beazley). You should really read it once you are up to speed on the basics.
|

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.