python logo

python find in array


Python hosting: Host, run, and code Python in the cloud!

Arrays are usually referred to as lists. For convience, lets call them arrays in this article.

Python has a method to search for an element in an array, known as index().
We can find an index using:


x = ['p','y','t','h','o','n']
print(x.index('o'))

Arrays start with the index zero (0) in Python:

python-string Python character array

If you would run x.index(‘p’) you would get zero as output (first index).

Related course:

Array duplicates: If the array contains duplicates, the index() method will only return the first element.

Find multiple occurences

If you want multiple to find multiple occurrences of an element, use the lambda function below.


get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

Find in string arrays

To find an element in a string array use:


x = ["Moon","Earth","Jupiter"]
print(x.index("Earth"))

You could use this code if you want to find multiple occurrences:



x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))


Find in numeric array

The index method works on numeric arrays too:


x = [5,1,7,0,3,4]
print(x.index(7))

To find multiple occurrences you can use this lambda function:



x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))







Leave a Reply: