Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sum(i for i in range(10))
#1
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?
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x axis range goes over the set range Pedroski55 5 3,224 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  Define a range, return all numbers of range that are NOT in csv data KiNeMs 18 7,079 Jan-24-2020, 06:19 AM
Last Post: KiNeMs

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020