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
List: [14, 7, 32, 9, 21, 45] 21 found at index 4 (position 5 in the list)
How it works
positionstarts at -1, a value that can never be a real index, to mean "not found yet".- The loop checks each index
iand comparesnumbers[i]withtarget. - On a match it saves the index and stops searching with
break. - 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()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises