Find Last Occurrence
Find the last occurrence with a Python index scan. Students update a saved position on every match and use minus one only as a not-found sentinel.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67x = int(input("Enter element to find: "))89# Find last occurrence10last_index = -111for i in range(len(arr)):12 if arr[i] == x:13 last_index = i1415if 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
In this one
- Use a not-found marker
- Keep the latest match
- Search every position
How it works
- 1
Initialize last_index to -1.
- 2
Replace it at each index whose value equals x.
- 3
Print it only if the marker changed.
Edge cases
What if there is no match?
What if there is no match?
The marker stays -1 and Element not found prints.
What if x occurs at index zero only?
What if x occurs at index zero only?
Zero replaces the marker and is reported correctly.
What's going on
last_index begins at -1 to mean no match has been seen. The loop visits indexes in increasing order.
Every equality replaces the saved index, so the final one is the last match. The final condition checks the sentinel before printing. Although -1 is a valid Python indexing expression, here it is just a stored marker, not used to access the list.
What if there is no match? The marker stays -1 and Element not found prints.
What if x occurs at index zero only? Zero replaces the marker and is reported correctly.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why not break at the first match?
Pick an answer to check it.
Question 2
What if there is no match?
Pick an answer to check it.
Questions people ask
What if there is no match?
The marker stays -1 and Element not found prints.
What if x occurs at index zero only?
Zero replaces the marker and is reported correctly.
Why not break at the first match?
Later matches must still be found.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum