[Tutor] Python Generator expressions
Animesh Bhadra
animeshb.social at gmail.com
Tue Jul 23 13:06:01 EDT 2019
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")
# 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
More information about the Tutor
mailing list