Yingjie Lan <lany...@yahoo.com> writes: > Hi, > > it seems a generator expression can be used only once: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> for x in g: print x #nothing printed >>>> > > Is there any way to revive g here? >
Generators are like that - you consume them until they run out of values. You could have done [x*x for x in range(3)] and then iterated over that list as many times as you wanted. A generator doesn't have to remember all the values it generates so it can be more memory efficient that a list. Also it can, for example, generate an infinite sequence. -- http://mail.python.org/mailman/listinfo/python-list