# Define a list of numbers numbers = [5, 2, 3, 1, 4] # Find the index of the number 4 index = numbers.index(4) # Print the index print(index)
To find the index of an item in a list, you can use the index() method. This method takes the item as an argument and returns the index of the first occurrence of the item in the list.
The above code will print 4, which is the index of the number 4 in the numbers list. Note that if the item is not found in the list, the index() method will raise a ValueError. You can handle this error by using a try-except block, like this:
# Define a list of numbers numbers = [5, 2, 3, 1, 4] # Try to find the index of the number 6 try: index = numbers.index(6) except ValueError: index = -1 # Print the index print(index)This will print -1, indicating that the number 6 was not found in the numbers list.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.