dict.items() vs dict.iteritems and similar questions

Alex Martelli aleax at mac.com
Thu Mar 15 10:56:28 EDT 2007


Steve Holden <steve at holdenweb.com> wrote:

> bearophileHUGS at lycos.com wrote:
> > Laurent Pointal:
> >> you may prefer range/items when processing of the result
> >> value explicitly need a list (ex. calculate its length)
> > 
> > Creating a very long list just to know the len of an iterator is
> > barbaric, so sometimes I use this:
> > 
> > def leniter(iterator):
> >     if hasattr(iterator, "__len__"):
> >         return len(iterator)
> >     nelements = 0
> >     for _ in iterator:
> >         nelements += 1
> >     return nelements
> > 
> Of course this is a little like the Heisenberg uncertainty principle if
> the iterator has no __len__ attribute - once you know how long it is you
> no longer have access to the elements. Or did I miss something?

Right.  However, "return sum(1 for _ in iterator)" may be a handier way
to express the same desctructive semantics as the last 4 lines here.


Alex



More information about the Python-list mailing list