Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

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

In this one

  • Guard a potentially failing lookup
  • Read zero-based indexes
  • Choose the first match

How it works

  1. 1

    Test x in arr.

  2. 2

    If present, call arr.index(x).

  3. 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.