Skip to content Skip to sidebar Skip to footer

Get Length Of A (non Infinite) Iterator Inside It's Loop Using Python 2.7

I'm working with some iterator generated using itertools.imap, and I was thinking if there is a way to access the iterator length inside the for-loop that I use to loop over the el

Solution 1:

I don't know if my idea is correct but how about class generator pattern and trying to add sequence bahaviour :

if your class represents something that has a length, don't define a GetLength method; define the __len__ method and use len(instance).

something like this :

classfirstn(object):
    def__init__(self, n):
        self.n = n
        self.num, self.nums = 0, []

    def__iter__(self):
        return self

    # Python 3 compatibilitydef__next__(self):
        return self.next()

    #    V------- Something like this def__len__(self):
        return self.my_length

    defnext(self):
        if self.num < self.n:
            cur, self.num = self.num, self.num+1return cur
        else:
            raise StopIteration()

Solution 2:

Also, because the information I'm looping are from a query to a database, I can get the length of the information from there, but the function I'm using has to return an iterator.

Assuming you have a good database, do the count there. Doubt any solution in python will be faster/cleaner.

Post a Comment for "Get Length Of A (non Infinite) Iterator Inside It's Loop Using Python 2.7"