[Python-ideas] list.index() extension

Leif Walsh leif.walsh at gmail.com
Sun Apr 5 11:11:06 CEST 2009

On Sun, Apr 5, 2009 at 4:01 AM, spir <denis.spir at free.fr> wrote:
> An issue is imo that (idx for idx, elt in enumerate(lst) if elt is obj) builds a generator able to yield every indexes of elements that satisfy the condition; while all you want is the first one (as expressed by ".next()").

It appears you're right, but the pain is only felt when the item is very close to the front of the list (and note that the ~2s penalty is over a million runs).

I've attached my benchmark, and the results are below.  For a quick idea of what I did, I made a simple global find(lst, obj) that has the 'is' condition hard-coded (for my own sanity).  I also used the generator example I posted above.  Each version was asked to find the last element of a list.  Times were averaged over 5 runs for each size, and the number of calls varied inversely to the size of the list (just so my computer doesn't burn out).

Running tests, each output in secs, average of 5 calls.
10 item list, 1000000 calls:
  gen:  5.534338
  fun:  3.620335
100 item list, 100000 calls:
  gen:  2.331217
  fun:  2.258001
1000 item list, 10000 calls:
  gen:  1.842553
  fun:  2.014453
10000 item list, 1000 calls:
  gen:  1.760938
  fun:  1.925302
100000 item list, 100 calls:
  gen:  1.783202
  fun:  1.921334
1000000 item list, 10 calls:
  gen:  1.798051
  fun:  1.955751


-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.py
Type: text/x-python
Size: 916 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090405/31586e86/attachment.py>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 270 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090405/31586e86/attachment.pgp>

More information about the Python-ideas mailing list