Master Python data types with this comprehensive guide. Learn about numeric, string, boolean, and collection data types with examples, exercises, and tasks. Perfect for beginners and professionals to enhance their Python programming skills.
The index()
method in Python is used with lists (and also works on tuples and strings) to find the position of the first occurrence of a given element.
index()
We use the index()
method when we want to find the position (index number) of an item in a list. This is helpful when:
list_name.index(element, start, end)
element
: The item to search for.start
(optional): Start searching from this index.end
(optional): Stop searching at this index (exclusive).fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana")) # Output: 1
It returns 1
because the first occurrence of "banana"
is at index 1.
print(fruits.index("orange")) # Error!
This will raise a ValueError
because "orange"
is not in the list.
print(fruits.index("banana", 2)) # Output: 3
This starts searching from index 2 and finds the second "banana"
at index 3.
Suppose you are building a to-do list app and you want to know where a task is located:
tasks = ["Buy groceries", "Do laundry", "Pay bills", "Call mom"]
task_to_find = "Pay bills"
position = tasks.index(task_to_find)
print(f"'{task_to_find}' is at position {position}")
🟢 Output:
'Pay bills' is at position 2
This could help you highlight the task in the app or remove it after completion.