How to find an item in list with Python?

Estimated read time 2 min read

To find an item in a list in Python, you can use the index() method or a loop to iterate over the list. Here are examples of both approaches:

Using the index() method:

my_list = [1, 2, 3, 4, 5]
item = 3

try:
    index = my_list.index(item)
    print(f"Item found at index {index}")
except ValueError:
    print("Item not found")

In this example, we use the index() method on the list my_list to find the index of the item we’re searching for. If the item is found, the method returns the index, which we then print. If the item is not found, the method raises a ValueError, which we catch with a try-except block and print a corresponding message.

Using a loop:

my_list = [1, 2, 3, 4, 5]
item = 3
found = False

for index, value in enumerate(my_list):
    if value == item:
        print(f"Item found at index {index}")
        found = True
        break

if not found:
    print("Item not found")

In this example, we iterate over the list my_list using a for loop and enumerate() to get both the index and value of each element. We compare each element with the item we’re searching for, and if a match is found, we print the index and set the found flag to True. If no match is found, we print a corresponding message based on the value of the found flag.

Both approaches accomplish the task of finding an item in a list, but the choice of which one to use depends on your specific requirements and the complexity of the code you want to write.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply