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

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Mar 15 06:48:44 EDT 2007


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

Bye,
bearophile




More information about the Python-list mailing list