On 7/23/19 11:06 AM, Animesh Bhadra wrote: > Hi All, > > Need one help in understanding generator expression/comprehensions. > > This is my sample code. > > # This code creates a generator and not a tuple comprehensions. > my_square =(num *num fornum inrange(11)) > print(my_square) # <generator object <genexpr> at 0x7f3c838c0ca8> > # We can iterate over the square generator like this. > try: > whileTrue: > print(next(my_square)) # Prints the value 0,1,4.... > exceptStopIterationasSI: > print("Stop Iteration")
is this code you were actually running? because it won't work... an except needs to be matched with a try, it can't match with a while. you *can* comsume your the values your generator expression generates by doing a bunch of next's, but why would you? Instead, just iterate over it (every generator is also an iterator, although not vice versa): for s in my_square: print(s) you don't have to manually catch the StopIteration here, because that's just handled for you by the loop. > # Another iteration > forx inmy_square: > print(x) # This prints nothing. > > > Does the generator exhausts its values when we run the iterator once? > Lastly any specific reason for not having a tuple comprehensions? > > Have checked this link, but could not understood the reason? > > * > https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python > > > Regards, > Animesh > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor