Find Last Occurrence

Find index of last occurrence of element.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 4 of 10
find-last-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 last occurrence
10last_index = -1
11for i in range(len(arr)):
12 if arr[i] == x:
13 last_index = i
14
15if last_index != -1:
16 print(f"Last occurrence at index: {last_index}")
17else:
18 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
Last occurrence at index: 3

What's going on

Iterate and track last matching index.

Key Concepts:

Loop through array
Update last_index when found
Track last occurrence