python find index of nth occurrence in list

Solutions on MaxInterview for python find index of nth occurrence in list by the best coders in the world

showing results for - "python find index of nth occurrence in list"
Lisa
02 Aug 2016
1# Basic syntax using list comprehension:
2[i for i, n in enumerate(your_list) if n == condition][match_number]
3# Where:
4#	- This setup makes a list of the indexes for list items that meet
5#		the condition and then match_number returns the nth index
6#	- enumerate() returns iterates through your_list and returns each
7#		element (n) and index value (i)
8
9# Example usage:
10your_list = ['w', 'e', 's', 's', 's', 'z','z', 's']
11[i for i, n in enumerate(your_list) if n == 's'][0]
12--> 2
13# 2 is returned because it is the index of the first element that
14#	meets the condition (being 's')