[Tutor] when is a generator "smart?"
Jim Mooney
cybervigilante at gmail.com
Sun Jun 2 05:58:38 CEST 2013
It's a little unclear to me where generators are more efficient. Below
I'm creating a list of non-even squares. I figured Python would be
smart enough to see I only wanted a small slice of a large generated
list, but as I increased y, Py got slower and eventually died of a
memory error. If I don't make it into a list I get a type error. So
where are generators more efficient? Or more specifically, how would i
make this efficient and use the generator to only pick out the small
2:10 slice I really want, but leave the capability of the entire list
if I wanted to slice and dice it in different ways further on?
def uneven_squares(x,y):
squarelist = (c**2 for c in range(x,y) if c%2 != 0)
return squarelist #returning a generator
print(list(uneven_squares(10,10000))[2:10]) #slows as y gets bigger, then dies
--
Jim
Ornhgvshy vf orggre guna htyl
More information about the Tutor
mailing list