Python String index() Method
The index() method is a list method that returns the position of the first occurrence of a given element in the list.
For example:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits.index("cherry"))
# prints 2
You can also specify a start and end index to limit the search range.
For example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(numbers.index(5, 3))
# prints 4
print(numbers.index(5, 3, 6))
# prints 4
If the element is not found in the list, a ValueError exception is raised.
For example:
animals = ["cat", "dog", "bird", "fish"]
print(animals.index("lion"))
# raises ValueError: 'lion' is not in list
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment