Editor

Python Program to Search for an Element in a List

Beginner · Searching and sorting · CBSE class 11 practical list

This program looks for a value in a list by checking the elements one by one from the start, a method called linear search. It reports the position where the value was found, or says that it is not in the list.

Program

search_in_list.py
numbers = [14, 7, 32, 9, 21, 45]
target = 21 # or: target = int(input("Enter the number to search for: "))
position = -1 # -1 means "not found yet"
for i in range(len(numbers)):
if numbers[i] == target:
position = i
break # stop at the first match
print("List:", numbers)
if position != -1:
print(f"{target} found at index {position} (position {position + 1} in the list)")
else:
print(target, "is not in the list")
Output
List: [14, 7, 32, 9, 21, 45]
21 found at index 4 (position 5 in the list)

How it works

  1. position starts at -1, a value that can never be a real index, to mean "not found yet".
  2. The loop checks each index i and compares numbers[i] with target.
  3. On a match it saves the index and stops searching with break.
  4. Python counts positions from 0, so the program prints both the index and the position counted from 1.

Other ways to write it

Using in and index()

Using in and index()
numbers = [14, 7, 32, 9, 21, 45]
target = 21
if target in numbers:
print(target, "found at index", numbers.index(target))
else:
print(target, "is not in the list")
Output
21 found at index 4

in tells you whether the value exists and index() returns where it first appears; index() raises an error for a missing value, so check with in first.

Finding every match in a tuple

Finding every match in a tuple
names = ("Ravi", "Anu", "Kiran", "Anu", "Meera")
target = "Anu"
positions = []
for i, name in enumerate(names):
if name == target:
positions.append(i)
if positions:
print(target, "found at indexes", positions)
else:
print(target, "is not in the tuple")
Output
Anu found at indexes [1, 3]

enumerate() gives each index together with its element, so the loop can collect every position where the value appears; a tuple is searched exactly like a list.

Try it yourself

Set target to 50 to see the "not in the list" message.

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.

All Python programs · CBSE class 12 practical file · Python exercises