-4

I have this generator which returns a list of numbers.

li=tile_generator(im)

I need to find the length of the list "li" as I need to check for a threshold value.
I used length = sum(1 for i in li). It is returning the length of the list but the elements in the generator are exhausted as it is a generator.
I need to return the length without exhausting the elements in the generator.

falsetru
  • 357,413
  • 63
  • 732
  • 636
Ashwin Raju
  • 155
  • 4
  • 12
  • 2
    This has been answered in great detail a few times on this site: http://stackoverflow.com/questions/7460836/how-to-lengenerator, http://stackoverflow.com/questions/393053/length-of-generator-output – Christopher Reid Feb 16 '16 at 02:14

1 Answers1

1

You can't do that. You can, however, turn it into a list first:

li = list(tile_generator(im))
length = len(li)
zondo
  • 19,901
  • 8
  • 44
  • 83
  • yes,but my concern is to use generator because i want to free away the elements when read. If i change it to list then i would be having unnecessary memory load. – Ashwin Raju Feb 16 '16 at 02:16
  • My point is that you cannot find the length of a generator without exhausting it. I can suggest, however, that maybe you are looking for `enumerate()`. You could say, for example, `for i, item in enumerate(tile_generator(im)):` and put any code you want in there. Once you are finished in your `for` loop, `i` will be the same as the length of the generator minus one. If you need the length *before* you use the generator, however, my answer is the only way. – zondo Feb 16 '16 at 02:19