Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i move the offset of the 'index' method of 'list'

i know that the index function work like this:

list = ['dog','cat','pizza','trump', 'computer', 'trump']
print list.index('trump')

the output will be 3. but now i want him for print the other 'trump' string, that come after 2 objects. but if i will do the same command:

print list.index('trump')

he will print 3 again - the first trump he see. so how do i move the 'offset' of the index function, so she will detect the other trump, in the index 5? thanks lot you guys!!

like image 589
Gerimeni Avatar asked May 23 '17 14:05

Gerimeni


2 Answers

list.index takes a 2nd start argument:

>>> lst = ['dog','cat','pizza','trump', 'computer', 'trump']
>>> lst.index('trump') # 1st index
3
>>> lst.index('trump',4) # 2nd index
5
>>> lst.index('trump',lst.index('trump')+1) # 2nd index
5

Or if you want all indexes, use a list comprehension:

>>> [idx for idx,item in enumerate(lst) if item == 'trump']
[3, 5]
like image 160
Chris_Rands Avatar answered Oct 21 '22 07:10

Chris_Rands


Just note the first index where the string appears, and pass the extra parameter to index the second time:

l = ['dog','cat','pizza','trump', 'computer', 'trump']
i = l.index("trump")
print(i)
print(l.index("trump",i+1))

I get:

3
5

from the inline doc, you can pass an optional start & stop value:

index(...)

L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.

(in a general case you have to protect your call to index by a try/except ValueError block in case the value is not in the list and act accordingly)

Note that start can be negative. If negative, the index is computed from the end of the list instead.

like image 37
Jean-François Fabre Avatar answered Oct 21 '22 09:10

Jean-François Fabre