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

Steve Holden steve at holdenweb.com
Thu Mar 15 13:04:18 CET 2007

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?

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com
See you at PyCon?         http://us.pycon.org/TX2007

More information about the Python-list mailing list