Find the index of the n'th item in a list Find the index of the n'th item in a list numpy numpy

Find the index of the n'th item in a list


The answer from @Taymon using list.index was great.

FWIW, here's a functional approach using the itertools module. It works with any iterable input, not just lists:

>>> from itertools import compress, count, imap, islice>>> from functools import partial>>> from operator import eq>>> def nth_item(n, item, iterable):        indicies = compress(count(), imap(partial(eq, item), iterable))        return next(islice(indicies, n, None), -1)

The example is nice because it shows off how to effectively combine Python's functional toolset. Note, that once the pipeline is set-up, there are no trips around Python's eval loop -- everything gets done at C speed, with a tiny memory footprint, with lazy evaluation, with no variable assignments, and with separately testable components. IOW, it is everything functional programmers dream about :-)

Sample run:

>>> x = [False,True,True,False,True,False,True,False,False,False,True,False,True]>>> nth_item(50, True, x)-1>>> nth_item(0, True, x)1>>> nth_item(1, True, x)2>>> nth_item(2, True, x)4>>> nth_item(3, True, x)6


I can't say for certain that this is the fastest way, but I imagine it'd be pretty good:

i = -1for j in xrange(n):    i = x.index(True, i + 1)

The answer is i.


[y for y in enumerate(x) if y[1]==True][z][0]

Note: Here Z is the n'th occurance,