Python Program to Find the First and Last Position of an Element
Intermediate · Searching and sorting
When a value appears several times in a list, its first occurrence is the lowest index where it appears and its last occurrence is the highest. This program finds both with one pass through the list, and the alternatives show the fast binary search version used for sorted lists.
Program
List: [5, 7, 7, 8, 8, 8, 10] First position of 8: index 3 Last position of 8: index 5
How it works
firstandlaststart at -1, a value that can never be a real index.- The first time the target is found,
firstis still -1, so it is set to that index and never changed again. lastis updated at every match, so after the loop it holds the index of the final one.- If the target never appears, both stay -1 and the program says so.
- This works for any list, sorted or not.
Other ways to write it
Binary search on a sorted list
First 8 at index 3 Last 8 at index 5
An ordinary binary search stops at any match. This one remembers the match and keeps searching to the left (for the first) or to the right (for the last).
Using index() on the list and its reverse
First index: 3 | Last index: 5
index() only finds the first match, so searching the reversed list finds the last one, counted from the end, and the subtraction turns it back into a normal index.
Try it yourself
Set target to 6 to see the "not in the list" message, then to 10.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises