Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStephen Cole
Courses Plus Student 15,809 PointsWhat is the for loop inside the sum function called?
In the final example, Kenneth creates a function that calculates the sum function that seems to do a list comprehension. What is it and why does it work?
1 Answer
Chris Freeman
Treehouse Moderator 68,453 PointsIt like a list comprehension, but in this case it is a generator expression. It behaves much like a list comprehension, but gives the advantage of a generator in terms of minimal memory usage.
# standard list comprehension
>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]
# generator expression - using parens instead of square brackets
>>> (x**2 for x in range(5))
<generator object <genexpr> at 0x000000000119D8E0>
# expand generator using list
>>> list(x**2 for x in range(5))
[0, 1, 4, 9, 16]
# using list comprehension as an argument to sum()
>>> sum([x**2 for x in range(5)])
30
# using generator expression (without square brackets)
>>> sum(x**2 for x in range(5))
30
# Not in a comprehension or generator context is a syntax error
>>> x**2 for x in range(5)
File "<stdin>", line 1
x**2 for x in range(5)
^
SyntaxError: invalid syntax