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?

Verbal_Kint
  • 1,366
  • 3
  • 19
  • 35

1 Answers1

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.

spinlok
  • 3,561
  • 18
  • 27
  • I will vote this up if you don't shadow the built in sum() function, and add the proper return statement – jdi May 02 '12 at 04:48
  • 2
    Well this was the way we did it before `sum()` existed – John La Rooy May 02 '12 at 04:48
  • in other languages, this would be easier to write, because `operator.plus` would be in the default namespace – ninjagecko May 02 '12 at 04:54
  • 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 May 02 '12 at 04:57
  • 1
    @Verbal_Kint, start with [this stackoverflow question](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for). IMO one of the best resources on python generators is http://www.dabeaz.com/generators/ (written by David Beazley). You should really read it once you are up to speed on the basics. – spinlok May 02 '12 at 05:04
  • `from operator import add` would work faster than a lambda function. – Joel Cornett May 02 '12 at 06:16