Emad Nawfal wrote: > Hi Tutors, > Is there a way to get the index of every occurence of a certain element > in a list. listname.index(element) gives me the index of the first > occurence. For example: > > >>> t = 'we are we are we we we'.split()
> Now I want the index of each 'we' in t. I want the result to be 0, 2, 4, > 5, 6 In [1]: t = 'we are we are we we we'.split() In [2]: [i for i, x in enumerate(t) if x=='we'] Out[2]: [0, 2, 4, 5, 6] Or, IMO a bit awkward but you could do this: In [3]: [i for i in range(len(t)) if t[i]=='we'] Out[3]: [0, 2, 4, 5, 6] In [4]: filter(lambda i: t[i]=='we', range(len(t))) Out[4]: [0, 2, 4, 5, 6] Kent _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
