Finding values on sequences and .index()

Donald O'Donnell donod at home.com
Wed Dec 6 22:33:58 EST 2000


rhamorim at my-deja.com wrote:
> 
> Hi.
> 
> I have a list that may have many ocurrences of the same data. How do I
> find the indexes for all ocurrences of it? list.index(value) only works
> for the first ocurrence.
...

How about using a list comprehension (ver 2.0) like this:

>>> a = [1, 2, 3, 4, 1, 5, 6, 7, 1, 8, 9, 1]
>>> n = 1
>>> x = [i for i in range(len(a)) if a[i]==n]
>>> x
[0, 4, 8, 11]

Or doing it the old fashioned way (ver 1.5):

>>> x = []
>>> for i in range(len(a)):
... 	if a[i] == n: x.append(i)
...
>>> x
[0, 4, 8, 11]

Hope this helps.

Don



More information about the Python-list mailing list