A contact list needs the position of a particular name.
What You Need to Understand
Searching with an explicit loop can return both the value and its position. enumerate() keeps the index aligned with each element.
When to Use It
A contact list needs the position of a particular name.
Step-by-Step Python Example
contacts = ["Maya", "Avi", "Noa"]
target = "Noa"
found_index = None
for position, contact in enumerate(contacts):
if contact == target:
found_index = position
break
print(found_index)
How the Example Works
The loop stops when it finds Noa and returns its zero-based index, 2.
Example Output
2
[0, 2]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
status = ["ok", "retry", "ok"]
print([index for index, value in enumerate(status) if value == "ok"])
Important Behavior and Edge Cases
Using None for a missing position is safer than accidentally treating index 0 as false. A list may contain duplicates, so define whether you want the first or all matches.
Try It Yourself
Find every position of a repeated status instead of only its first occurrence.
Common Beginner Mistakes
- Using
Nonefor a missing position is safer than accidentally treating index 0 as false. A list may contain duplicates, so define whether you want the first or all matches. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Searching with an explicit loop can return both the value and its position.
- The loop stops when it finds
Noaand returns its zero-based index, 2. - Using
Nonefor a missing position is safer than accidentally treating index 0 as false.