list.index() like...but returning lists (for avoiding '0' on multiples hits)
Dang Griffith
noemail at noemail4u.com
Tue Dec 23 10:27:54 EST 2003
On Mon, 22 Dec 2003 17:37:46 -0300, Gerardo Herzig -Departamento de
Proyectos Especiales e Internet- Facultad de Medicina
<gherzig at fmed.uba.ar> wrote:
>Hi....i asume this is a veeeery usual question. I'm searching on python.org,
>but their results is not giving me the answer that i looking for...So, here i
>go...when i have myList = [2,4,2,0] ...myList.index(2) returns 0 (python
>2.2)....There is a built-in function-method that returns [0,2]?
>
>Well, sory if RTFM is the answer!!
Do you mean a function that returns a list of the indices of all
occurrences of the specified value? I don't think there's a builtin,
but you could do something like this:
def indices(lst, val):
""" Return a list of indices of matches. """
return [i for i in range(0, len(lst)) if lst[i] == val]
myList = [2, 4, 2, 0]
print indices(myList, 2)
# [0, 2]
--dang
More information about the Python-list
mailing list