Print the index of a specific item in a list?
Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
In Python, you find the index of an element in a list using the list.index() method:
technologies = ['React', 'Python', 'Docker', 'PostgreSQL']
# Finding the index
idx = technologies.index('Docker')
print(f"Index of Docker: {idx}") # Output: Index of Docker: 2
### Handling Missing Items Safely:
If the item does not exist in the list, list.index() raises a ValueError. Prevent crashes using in check or try/except:
search_target = 'GraphQL'
if search_target in technologies:
print(technologies.index(search_target))
else:
print(f"'{search_target}' not found in list.")
### Enumerating While Iterating:
To print both the index and value during iteration, use the built-in enumerate() function:
for idx, tech in enumerate(technologies):
print(f"#{idx}: {tech}")
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.