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

Guido van Rossum guido at python.org
Fri Sep 4 23:08:03 CEST 2009


More likely the cost of the two dynamic lookups of builtin functions
is your cost.

On Fri, Sep 4, 2009 at 12:56 PM, Gerald Britton<gerald.britton at gmail.com> wrote:
> Interesting that your return(next()) example runs about 60% slower
> than the "for x in l: return x" example.  Must be the function call
> overhead.
>
> On Fri, Sep 4, 2009 at 3:36 PM, Stefan Behnel<stefan_ml at behnel.de> wrote:
>> 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]'
>>                      'getany(l)'
>> 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' \
>>                      'getany(l)'
>> 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))' \
>>                      'getany(l)'
>> 1000000 loops, best of 3: 0.743 usec per loop
>>
>>
>> but, admittedly, that's still not slow in absolute numbers.
>>
>> Stefan
>>
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> http://mail.python.org/mailman/listinfo/python-ideas
>>
>
>
>
> --
> Gerald Britton
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list