need to get an index for an item in a list

Peter Hansen peter at engcorp.com
Sun Jul 3 15:48:10 EDT 2005


Roy Smith wrote:
> That being said, index() isn't isn't going to work if there are duplicate 
> lines in the file; it'll return the index of the first one.

It will still work, if you are willing to do a bit of work to help it:

 >>> l = range(10) + [5]
 >>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5]
 >>> l.index(5)
5
 >>> l.index(5, 5+1)
10

As with str.index(), the one for list takes a second argument that 
specifies the index at which to start the search, allowing you to skip 
past items that have already been checked.

That said, other approaches (such as Roy suggested in his other post) 
may well be more appropriate depending on the context.

-Peter



More information about the Python-list mailing list