I’m familiar with the for loop in a block-code context. eg:
for c in "word":
print c
I just came across some examples that use for differently. Rather than beginning with the for statement, they tag it at the end of an expression (and don’t involve an indented code-block). eg:
sum(x*x for x in range(10))
Can anyone point me to some documentation that outlines this use of for? I’ve been able to find examples, but not explanations. All the for documentation I’ve been able to find describes the previous use (block-code example). I’m not even sure what to call this use, so I apologize if my question’s title is unclear.
What you are pointing to is
Generatorin Python. Take a look at: –See the documentation: –
Generator Expressionwhich contains exactly the same example you have postedFrom the documentation: –
Generators are similar to
List Comprehensionthat you use withsquare bracketsinstead ofbrackets, but they are more memory efficient. They don’t return the completelistof result at the same time, but they return generator object. Whenever you invokenext()on thegeneratorobject, the generator usesyieldto return the next value.List Comprehensionfor the above code would look like: –You can also add conditions to filter out results at the end of the for.
This will return a list of
numbersmultiplied by 2 in the range 1 to 5, if the number is not divisible by 2.An example of
Generatorsdepicting the use ofyieldcan be: –So, you see that, every call to
next()executes the nextyield()ingenerator. and at the end it throwsStopIteration.