How to find the length of itertools.izip_longest

I have many tuples stored in 'itertools.izip_longest'

I am trying to loop through these tuples contained in itertools.izip_longest to change some values ​​as shown in the code below

for i in range(len(pixels)):
  if i >= 2148 and i <= 3505:
    if pixels[i][0] == 146: # assuming each data element is a 3 element tuple
     pixels[i][0] += 1

      

however, when I try to run the code, I get an error related to length:

  for i in range(len(pixels)):
TypeError: object of type 'itertools.izip_longest' has no len()

      

how can i find the length (number of tuples) contained in the itertools.izip_longest file

thank

+3


source to share


2 answers


Technically you can't, because it's a generator. After an element is called, it is generated on the fly. This makes things more dynamic and uses less memory in some cases. In the case of zipping, you are not making a copy of the lists, but the generator generates tuples on the fly.

However, you can use it to enforce what it has len

as a list:

pixels = list(pixels)

      

What it means is it consumes a generator and makes a list with the same name. (After the generator is generated, the list will be consumed, so there is no point in leaving it around.) Please remember this is a slightly different object and this is not always suitable performance. You can usually calculate and store the cardinality before anti-aliasing without creating additional objects.



By the way, why don't you just iterate over the pixels you want?

pixels = list(pixels)
for pixel in pixels[2148:3505]:
  if pixel[0] == 146:
    pixel[0] += 1

      

Now you are doing 2148 iterations that are guaranteed to do nothing.

+1


source


izip_longest

returns a generator , where each returned element is generated on the fly. If you want to know how many elements are in an iterable, you can do

len(list(pixels))

      

This is the same as



len([item for item in pixels])

      

Example:

In [1]: from itertools import izip_longest

In [2]: x = izip_longest(range(10), range(100))

In [3]: len(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e62f33f06233> in <module>()
----> 1 len(x)

TypeError: object of type 'itertools.izip_longest' has no len()

In [4]: len(list(x))
Out[4]: 100

      

+2


source







All Articles