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!!
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With