Given:
x = ['w', 'e', 's', 's', 's', 'z','z', 's']
Each occurrence of s
appears at the following indices:
1st: 2
2nd: 3
3rd: 4
4th: 7
If I do x.index('s')
I will get the 1st index.
How do I get the index of the 4th s
?
To get every nth element in a list, a solution is to do mylist[::n].
To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.
Using index We can design a for loop to access the elements from the list with the in clause applied for nth index.
To find the index of nth occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times. There could be a requirement in your Java application, that you have to find the position of the nth occurrence of str2 in str1 .
Using list comprehension and enumerate
:
>>> x = [ 'w', 'e', 's', 's', 's', 'z','z', 's'] >>> [i for i, n in enumerate(x) if n == 's'][0] 2 >>> [i for i, n in enumerate(x) if n == 's'][1] 3 >>> [i for i, n in enumerate(x) if n == 's'][2] 4 >>> [i for i, n in enumerate(x) if n == 's'][3] 7
If you didn't want to store the indices for each occurrence, or wanted to work with arbitrary iterables then something like:
from itertools import islice
def nth_index(iterable, value, n):
matches = (idx for idx, val in enumerate(iterable) if val == value)
return next(islice(matches, n-1, n), None)
x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
idx = nth_index(x, 's', 4)
# 7
Note there's a default value of None
there in the next
. You may wish to change that to something else, or remove it and catch the StopIteration
and raise as another more suitable exception (ValueError
for instance, so that it ties up more with list.index
behaviour).
For getting the index of the items:
return [index for index, char in enumerate(x) if char == 's']
For getting the character itself:
return [char for index, char in enumerate(x) if char == 's']
Or to get tuples of character/index pairs: (Thanks to falsetru for pointing out a simpler solution)
pairs = [(index, char) for index, char in enumerate(x) if char == 's']
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