Python Forum

Full Version: sum(i for i in range(10))
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The documentation for sum() states that it takes as its argument an iterable. How does this make sense of the code sum(i for i in range(10)), because the for loop isn't an iterable is it?
i for i in range(10) is generator expression (you can skip the brackets in this case), i.e. it's a iterable.

It's separate matter, that sum(range(10)) would do all the same - range object is iterable too
>>> sum(range(10))
45
for-loop creates iterable automagically. To find out what is going on use interactive interpreter built-in help (press q to quit help):

>>> help('for')
The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  [b]An iterator is created[/b] for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.
/...../
Result of this code can be achieved by less brute-force means as well. It may or may not be important but
triangular number is way to go for large numbers (note that this returns float due to division):

>>> 9 * (9 + 1) / 2
45.0