Find First Occurrence
Find the first occurrence of an integer in a list. Students guard list.index with membership and learn the difference between zero-based position and frequency.
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 first occurrence10if 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
In this one
- Guard a potentially failing lookup
- Read zero-based indexes
- Choose the first match
How it works
- 1
Test x in arr.
- 2
If present, call arr.index(x).
- 3
Print that index or the not-found message.
Edge cases
What if x is absent?
What if x is absent?
The program prints Element not found instead of calling index.
Which repeated match is selected?
Which repeated match is selected?
The first occurrence.
What's going on
The membership test runs before arr.index(x). That guard avoids calling index on a value that is absent.
When found, index returns the earliest equal position, starting from zero. Duplicates later in the list do not change the answer. This version scans for membership and then scans again for the first position, favoring simple teaching over a single-pass search.
What if x is absent? The program prints Element not found instead of calling index.
Which repeated match is selected? The first occurrence.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is the membership guard useful?
Pick an answer to check it.
Question 2
What if x is absent?
Pick an answer to check it.
Questions people ask
What if x is absent?
The program prints Element not found instead of calling index.
Which repeated match is selected?
The first occurrence.
Why is the membership guard useful?
index would raise ValueError for an absent value.
๐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