Rich
Rich

Reputation: 53

How to find the length of itertools.izip_longest

i have many tuples stored within a 'itertools.izip_longest'

i am trying to loop through these tuples contained withinthe itertools.izip_longest to alter 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 relating to the 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 within the itertools.izip_longest

thanks

Upvotes: 3

Views: 850

Answers (2)

luk32
luk32

Reputation: 16080

Technically you cannot, because it's a generator. Upon call for an element it is generated on the fly. This allows to make things more dynamic, and use less memory in certain cases. In case of zipping you don't generate a copy of the lists, but generator generates tuples on the fly.

However, you can use it to insantiate something that has len like a list:

pixels = list(pixels)

What this does is it consumes generator and makes a list under the same name. (After generating the list generator would be consumed, so there is no point in leaving it around.) Please remember it's a slightly different object, and it is not always suitable performance wise. Usually it is possible to compute and store the number of elements before zipping with out creating additional objects.

Btw why won't you just iterate over pixels that you need to?

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.

Upvotes: 1

wflynny
wflynny

Reputation: 18531

izip_longest returns a generator, where each item returned is generated on the fly. If you want to know how many items are in the 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

Upvotes: 2

Related Questions