list.index() like...but returning lists (for avoiding '0' on multiples hits)
francisgavila at yahoo.com
Tue Dec 23 01:07:41 CET 2003
John Roth wrote in message ...
>But what does that have to do with the question?
>As far as I know, there is no such built-in for lists.
>You can do something similar with the "re" module
>for strings, but not for lists.
More and more I am finding myself wishing for a neat way to *add*
functionality to a builtin. Not subclass a builtin, but add methods to the
Like (the function does what the OP wants, btw):
>>> def indices(self, value):
... return [i for i,v in enumerate(self) if v == value]
>>> list.indexes = indexes
>>> [0, 2, 2, 3].indexes(2)
This currently gives:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't set attributes of built-in/extension type 'list'
Oh well. Anyway, the following might be faster:
def indices2(L, value):
res = 
last = -1 #below, last+1 to prevent infinite loop.
last = L.index(value, last+1)
More information about the Python-list