List comprehension produce complete list with compact syntax:
[x**2 for x in xrange(1,10)] [x+y for x in xrange(1,10) for y in xrange(1,10)] [x-y for x in xrange(1,10) for y in xrange(1,10) if x>y] xlist = [x**2 for x in xrange(1,10)] print xlist[0], xlist[2], xlist[-1] print xlist[2:4] print sum(xlist), sum(xlist)
Generator expression produce generator with compact syntax:
(x**2 for x in xrange(1,10)) (x+y for x in xrange(1,10) for y in xrange(1,10)) print [x for x in (x**2 for x in xrange(1,10))] xgen = (x**2 for x in xrange(1,10)) try: xgen[0] except TypeError: print "'generator' object has no attribute '__getitem__'" print sum(xlist), sum(xlist)
Parentheses is required only if expression is ambiguous.