Python List - Find Index of an Element Using Wildcards

Python List - Find Index of an Element Using Wildcards

  • Python
  • 2 mins read

This Python tutorial shows you how to find an index of an element using wildcards, indexOf, and transpose and slice methods.

In Python, suppose you want to identify the index of an element in the list xyz based on the first three sub-elements of the element. For example, the index of the element which contains ['4','5','6'] as its first three sub-elements are 1. Below is the list:

xyz = [['1','2','3','a','b'],
     ['4','5','6','c','d'],
     ['7','8','9','e','f']]

Example 1: Finding Index of List Element Using TRUE Wildcard in Python

You can use xyz.index(...). If you use a true wildcard. Below is an example:

class Wildcard:
    def __eq__(self, anything):
        return True

xyz = [['1','2','3','a','b'],
     ['4','5','6','c','d'],
     ['7','8','9','e','f']]

wc = Wildcard()

print(xyz.index(['4', '5', '6', wc, wc]))

Output:

1

Example 2: Using operator.indexOf

You can also use operator.indexOf, which finds the index in C rather than in Python as an enumerate solution would.

from operator import indexOf, itemgetter

x = [['1','2','3','a','b'],
     ['4','5','6','c','d'],
     ['7','8','9','e','f']]

print(indexOf((r[:3] for r in x), ['4', '5', '6']))
print(indexOf(map(itemgetter(slice(3)), x), ['4', '5', '6']))

Output:

1
1

Example: 3 Using transpose and slice

Below is another example using transpose and slice. It transposes back and finds the index:

from operator import indexOf, itemgetter

x = [['1','2','3','a','b'],
     ['4','5','6','c','d'],
     ['7','8','9','e','f']]

print(list(zip(*list(zip(*x))[:3])).index(('4', '5', '6')))

Output:

1

Example 4: Using Generator

Find the first match and stop execution of the code:

x = [['1','2','3','a','b'],
     ['4','5','6','c','d'],
     ['7','8','9','e','f']]


pattern = ['4','5','6']

def find_index(data, pattern):
    for n, elt in enumerate(x):
        if elt[:3] == pattern:
            yield n

indices = find_index(x, pattern)
print(next(indices))

Output:

1