# 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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.