[Python-ideas] data structures should have an .any() method

Stefan Behnel stefan_ml at behnel.de
Fri Sep 4 21:36:57 CEST 2009

Guido van Rossum wrote:
> On Fri, Sep 4, 2009 at 2:35 AM, Stefan Behnel wrote:
>> I just had a discussion with a co-worker, and we noticed that there are use
>> cases where you just want the only element in a data structure, or just any
>> of the elements in a data structure because you know that they all contain
>> the same information (with respect to what you are looking for, at least).
>> If you want all items, you can iterate, but if you just want any item or
>> the only item, it's inefficient (and not very explicit code) to create an
>> iterator and take the element out.
> I assure you it's not slow.

Not in absolute numbers, but certainly slower than necessary:

$ python2.6 -m timeit -s 'l=[1]' 'l[0]'
10000000 loops, best of 3: 0.0977 usec per loop

$ python2.6 -m timeit -s 'l=[1]' 'next(iter(l))'
1000000 loops, best of 3: 0.523 usec per loop

> next(iter(x)) is probably as good as it
> gets -- I don't think we need another way to say that in fewer words.

I'm fine with such a decision, given that it's trivial to wrap this into
your own function. That doesn't make it much faster:

$ python2.6 -m timeit -s 'l=[1]' -s 'def getany(l):'
                                 -s '  return l[0]'
1000000 loops, best of 3: 0.34 usec per loop

$ python2.6 -m timeit -s 'l=[1]' -s 'def getany(l):' \
                                 -s '  for x in l:' \
                                 -s '    return x' \
1000000 loops, best of 3: 0.454 usec per loop

$ python2.6 -m timeit -s 'l=[1]' -s 'def getany(l):' \
                                 -s '  return next(iter(l))' \
1000000 loops, best of 3: 0.743 usec per loop

but, admittedly, that's still not slow in absolute numbers.


More information about the Python-ideas mailing list