Jump to content

List comprehensions: Difference between revisions

no edit summary
m (Moved to Basic learning cat)
No edit summary
Line 61:
List comprehension:
 
<lang python>[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]</pythonlang>
 
Generator comprehension (note the outer round brackets):
 
<lang python>((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2)</pythonlang>
 
Generator function:
 
<lang python>def gentriples(n):
for x in xrange(1,n+1):
for y in xrange(x,n+1):
for z in xrange(y,n+1):
if x**2 + y**2 == z**2:
yield (x,y,z)</pythonlang>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.