Finding values on sequences and .index()

rhamorim at my-deja.com rhamorim at my-deja.com
Thu Dec 7 07:01:18 EST 2000


Thanks, it does help. I was so worried about not using for loops that I
couldn't see those options. :-)

Best regards,

Roberto Amorim

In article <3A2F0531.EBFD0C72 at home.com>,
  Donald O'Donnell <donod at home.com> wrote:
> 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
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list