Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1079777
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T21:55:23+00:00 2026-05-16T21:55:23+00:00

I have an iterator with a __len__ method defined. Questions: If you call list(y)

  • 0

I have an iterator with a __len__ method defined. Questions:

If you call list(y) and y has a __len__ method defined, then __len__ is called.

   1) Why?

In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list, and on the second call I receive the “correct” list.

   2) Why is it returning a list of length zero at all?

   3) Why does the list length correct itself on all subsequent calls?

Also notice that calling “enumerate” is not the issue. Class C does the same thing but using a while loop and calls to next().

Code:

showcalls = False

class A(object):
    _length = None
    def __iter__(self):
        if showcalls:
            print "iter"
        self.i = 0
        return self        
    def next(self):
        if showcalls:
            print "next"
        i = self.i + 1
        self.i = i
        if i > 2:
            raise StopIteration
        else:
            return i

class B(A):
    def __len__(self):
        if showcalls:
            print "len"
        if self._length is None:
            for i,x in enumerate(self):
                pass
            self._length = i
            return i
        else:
            return self._length

class C(A):
    def __len__(self):
        if showcalls:
            print "len"
        if self._length is None:
            i = 0
            while True:
                try:
                    self.next()
                except StopIteration:
                    self._length = i
                    return i
                else:
                    i += 1
        else:
            return self._length

if __name__ == '__main__':
    a = A()
    print len(list(a)), len(list(a)), len(list(a))
    print
    b = B()
    print len(list(b)), len(list(b)), len(list(b))
    print
    c = C()
    print len(list(c)), len(list(c)), len(list(c))

Output:

2 2 2

0 2 2

0 2 2
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T21:55:23+00:00Added an answer on May 16, 2026 at 9:55 pm

    If you call list(y) and y has a
    len method defined, then len is called. why?

    Because it’s faster to build the resulting list with the final length, if known from the start, than to begin with an empty list and append one item at a time. And __len__ is, and must be, 100% guaranteed to be reliable.

    IOW, do not implement special methods like __len__ if and when you can’t return a reliable value.

    As for the second question, your implementations of __len__ are broken because they consume the iterator (and don’t return it to its pristine state) — so they leave no items for following .next calls, so the list constructor gets a StopIteration and decides that your __len__ was just flaky (it’s unfortunately flakier than poor list can guess…!-).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an iterator called myfor such that when I call myfor(3,7,X). I want
I have a custom iterator template class that wraps up a std::list iterator. In
I have a question regarding the iterator behavior in Java. I have a call
I have this simple code public String toString() { **Iterator it = list.iterator();** String
I have a list iterator that goes through a list and removes all the
I have a iterator which goes through a list and create their name and
I have three questions based on the following code fragments I have a list
In c++ STL, if I have an iterator it into a vector v ,
I have a row-major iterator to a 2D array, with derefence operator as follows:
I have this loop for (it= someCollection.iterator; it.hasNext(); ) { //some code here }

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.