Find First Occurrence

Find index of first occurrence of element.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 3 of 10
find-first-occurrence.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7x = int(input("Enter element to find: "))
8
9# Find first occurrence
10if x in arr:
11 index = arr.index(x)
12 print(f"First occurrence at index: {index}")
13else:
14 print("Element not found")

Output

Enter array size: 5
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 20
Element 5: 40
Enter element to find: 20
First occurrence at index: 1

What's going on

Use index() method to find first occurrence.

Key Concepts:

index(x) returns first index
Check existence first
Returns index of first match