I have a list with some values. I have a variable called 'five' which is 5. I want to look through the list for the value of 'five', get its index, and print it if present, otherwise print that it's not present. Any questions?
💡 Model Answer
To find the index of a value in a list you can perform a linear search. Iterate over the list with enumerate to get both index and element. If the element equals the target value (in this case 5), return or print the index and stop the loop. If the loop completes without finding the value, print a message that it is not present. The time complexity is O(n) because in the worst case you examine every element. The space complexity is O(1) as you only use a few variables. Example in Python:
my_list = [2, 4, 5, 7, 9]
value = 5
found = False
for idx, val in enumerate(my_list):
if val == value:
print(f"Value {value} found at index {idx}")
found = True
break
if not found:
print(f"Value {value} not found in the list")This code prints "Value 5 found at index 2" for the sample list.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500