A queue needs to locate the first occurrence of a task label.
What You Need to Understand
list.index(value, start=0, stop=len(list)) returns the position of the first matching element within an optional search interval.
When to Use It
A queue needs to locate the first occurrence of a task label.
Step-by-Step Python Example
queue = ["wait", "run", "wait"]
print(queue.index("wait"))
print(queue.index("wait", 1))
How the Example Works
The first match is at position 0; searching from index 1 finds position 2.
Example Output
0
2
2
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
colors = ["blue", "green", "blue"]
print(colors.index("blue", 1))
Important Behavior and Edge Cases
A missing value raises ValueError. Use value in items before lookup or handle the exception if missing values are expected.
Try It Yourself
Search for a repeated color only after the first position.
Common Beginner Mistakes
- A missing value raises
ValueError. Usevalue in itemsbefore lookup or handle the exception if missing values are expected. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
list.index(value, start=0, stop=len(list))returns the position of the first matching element within an optional search interval.- The first match is at position 0; searching from index 1 finds position 2.
- A missing value raises
ValueError.