How to Find the index of an item in a list in Python?

0
0

In Python, you can use the index() method to find the index of a specific item in a list. The syntax for using the index() method is list.index(x), where list is the list you want to search and x is the item you want to find the index of. If the item is not found in the list, a ValueError is raised.

Here’s an example:

my_list = [1, 2, 3, 4, 5, 6]
index = my_list.index(3)
print(index) # 2

In this example, we have a list my_list containing six integers. We use the index() method to find the index of the integer 3, which is 2 (remember that Python uses zero-based indexing).

If the item you’re looking for appears more than once in the list, the index() method returns the index of the first occurrence:

my_list = [1, 2, 3, 4, 3, 6]
index = my_list.index(3)
print(index) # 2

In this example, the integer 3 appears twice in the list, but the index() method returns the index of the first occurrence, which is still 2.

If the item you’re looking for is not in the list, a ValueError is raised:

my_list = [1, 2, 3, 4, 5, 6]
index = my_list.index(7) # Raises ValueError: 7 is not in list

 

In this example, we try to find the index of the integer 7, which is not in the list. This raises a ValueError with the message “7 is not in list”.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.