python return index of second match code example
Example 1: python return index of second match
# Example usage:
your_list = ['The answer to', 'the ultimate question', 'of life',
'the universe', 'and everything', 'is 42']
[idx for idx, elem in enumerate(your_list) if 'universe' in elem][0]
--> 3 # The 0-based index of the first list element containing "universe"
Example 2: python return index of second match
# Basic syntax using list comprehension:
[i for i, n in enumerate(your_list) if n == condition][match_number]
# Where:
# - This setup makes a list of the indexes for list items that meet
# the condition and then match_number returns the nth index
# - enumerate() returns iterates through your_list and returns each
# element (n) and index value (i)
# Example usage:
your_list = ['w', 'e', 's', 's', 's', 'z','z', 's']
[i for i, n in enumerate(your_list) if n == 's'][0]
--> 2
# 2 is returned because it is the index of the first element that
# meets the condition (being 's')
Example 3: python return index of second match
# Basic syntax:
list.index(element, start, end)
# Where:
# - Element is the item you're looking for in the list
# - Start is optional, and is the list index you want to start at
# - End is option, and is the list index you want to stop searching at
# Note, Python is 0-indexed
# Example usage:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 42, 9, 10]
my_list.index(42)
--> 8