• Linear: O(n) time complexity
• Binary: O(log n) for sorted lists
• index() method for built-in search
Search Element in List/Tuple
AIM
To write a Python program that inputs a list/tuple of elements and searches for a given element, displaying its index and position if found.
Note: Index starts from 0, while position starts from 1. Index is used in programming, position is more user-friendly.
ALGORITHM
- Start
- Initialize an empty list
- Input the number of elements from user
- Use a loop to input elements and append them to the list
- Display the entered list
- Input the element to be searched
- Use a loop to iterate through the list
- Compare each element with the search element
- If found, display the index and position, then break
- If loop completes without finding, display "not found" message
- Stop
PROGRAM
# Input a list/tuple of elements, search for a given element
# Method 1: Linear Search in List
lst = []
num = int(input("How many Numbers in the list: "))
for n in range(num):
numbers = int(input("Enter Number: "))
lst.append(numbers)
print("The Entered list is:", lst)
length = len(lst)
element = int(input("Enter the element to be searched for: "))
for i in range(0, length):
if element == lst[i]:
print(element, "found at index", i, "and position:", i + 1)
break
else:
print(element, "is not found!!!")
print("\n" + "=" * 50)
print("METHOD 2: Using Built-in Methods")
print("=" * 50)
# Method 2: Using built-in methods
lst2 = []
num2 = int(input("\nHow many Numbers in the list: "))
for n in range(num2):
numbers = int(input("Enter Number: "))
lst2.append(numbers)
print("The Entered list is:", lst2)
element2 = int(input("Enter the element to be searched for: "))
if element2 in lst2:
index = lst2.index(element2)
print(element2, "found at index", index, "and position:", index + 1)
# Count occurrences
count = lst2.count(element2)
print(f"Element {element2} appears {count} time(s) in the list")
# Find all occurrences
all_indices = [i for i, x in enumerate(lst2) if x == element2]
print(f"All indices where {element2} is found: {all_indices}")
else:
print(element2, "is not found!!!")
print("\n" + "=" * 50)
print("METHOD 3: Search in Tuple")
print("=" * 50)
# Method 3: Search in Tuple
tuple_elements = []
num3 = int(input("\nHow many elements in tuple: "))
for n in range(num3):
element_input = input("Enter element: ")
# Try to convert to int, if fails keep as string
try:
element_input = int(element_input)
except ValueError:
pass
tuple_elements.append(element_input)
my_tuple = tuple(tuple_elements)
print("The Entered tuple is:", my_tuple)
search_element = input("Enter the element to be searched for: ")
# Try to convert search element to int if possible
try:
search_element = int(search_element)
except ValueError:
pass
found = False
for i, item in enumerate(my_tuple):
if item == search_element:
print(f"{search_element} found at index {i} and position {i + 1}")
found = True
break
if not found:
print(f"{search_element} is not found in the tuple!!!")
print("\n" + "=" * 50)
print("METHOD 4: Function-based Search")
print("=" * 50)
def linear_search(data_list, target):
"""Function to perform linear search"""
for i, item in enumerate(data_list):
if item == target:
return i
return -1
def search_all_occurrences(data_list, target):
"""Function to find all occurrences of target"""
indices = []
for i, item in enumerate(data_list):
if item == target:
indices.append(i)
return indices
# Demo with predefined data
demo_list = [10, 20, 30, 20, 40, 20, 50]
print(f"\nDemo list: {demo_list}")
target = 20
result = linear_search(demo_list, target)
if result != -1:
print(f"First occurrence of {target} found at index {result}")
else:
print(f"{target} not found in the list")
all_occurrences = search_all_occurrences(demo_list, target)
if all_occurrences:
print(f"All occurrences of {target} at indices: {all_occurrences}")
print(f"Total occurrences: {len(all_occurrences}")
else:
print(f"{target} not found in the list")OUTPUT
How many Numbers in the list: 5
Enter Number: 10
Enter Number: 20
Enter Number: 30
Enter Number: 40
Enter Number: 50
The Entered list is: [10, 20, 30, 40, 50]
Enter the element to be searched for: 30
30 found at index 2 and position: 3
==================================================
METHOD 2: Using Built-in Methods
==================================================
How many Numbers in the list: 4
Enter Number: 5
Enter Number: 15
Enter Number: 25
Enter Number: 35
The Entered list is: [5, 15, 25, 35]
Enter the element to be searched for: 100
100 is not found!!!
==================================================
METHOD 4: Function-based Search
==================================================
Demo list: [10, 20, 30, 20, 40, 20, 50]
First occurrence of 20 found at index 1
All occurrences of 20 at indices: [1, 3, 5]
Total occurrences: 3
CONCLUSION
Thus, the given program was successfully executed and the output was verified as per the expected result.
VIVA QUESTIONS
What is the difference between index and position?
Index starts from 0 and is used in programming, while position starts from 1 and is more user-friendly. Position = Index + 1.
How does the for-else construct work in Python?
The else block executes only if the loop completes normally (without encountering a break). If break is executed, the else block is skipped.
What is the time complexity of linear search?
Linear search has O(n) time complexity in worst case, where n is the number of elements. Best case is O(1) when element is found at first position.
What happens if we use index() method on non-existent element?
The index() method raises a ValueError if the element is not found. That's why we use 'in' operator first to check existence.
How can you find all occurrences of an element?
Use list comprehension: [i for i, x in enumerate(lst) if x == target] or iterate through the list and collect all matching indices.
What is the difference between searching in list vs tuple?
The search algorithm is the same, but tuples are immutable. Lists can be modified during search, while tuples cannot. Both support indexing and iteration.
How would you implement binary search?
Binary search requires a sorted list and has O(log n) complexity. It repeatedly divides the search space in half by comparing with the middle element.
What is the advantage of using enumerate() function?
enumerate() returns both index and value in each iteration, making code cleaner than manually tracking index with range(len(list)).
Related Resources
- List Manipulation Python
- Search Algorithms Tutorial
- Python Search Methods PDF
- Search Algorithm MCQs
- Previous Program: List Swap
Search Tips
- • Use 'in' operator for simple existence checks
- • Handle ValueError when using index() method
- • Consider binary search for sorted data
- • Use enumerate() for index-value pairs