Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of the nth time an item appears in a list?

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?

like image 526
Rimoun Avatar asked Mar 08 '14 08:03

Rimoun


People also ask

How do you find the nth index of a list in Python?

To get every nth element in a list, a solution is to do mylist[::n].

How do you find the index value of an element in a list?

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.

How do you find the nth element in a list?

Using index We can design a for loop to access the elements from the list with the in clause applied for nth index.

How do you find the index of the nth occurrence of a substring in a string?

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 .


3 Answers

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 
like image 133
falsetru Avatar answered Sep 19 '22 20:09

falsetru


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).

like image 44
Jon Clements Avatar answered Sep 20 '22 20:09

Jon Clements


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']
like image 36
samrap Avatar answered Sep 22 '22 20:09

samrap