find() vs index() vs `in` — which one?
They do the same search and differ only in how they report a miss. find returns -1, index raises ValueError, and in returns a bool. Pick by whether a miss is expected (use find or in) or a bug (use index).
Overview
The same search, three reports
find returns the index of the first occurrence, or -1. index returns the same index, or raises ValueError. in answers only yes or no, and reads better when that is all you need.
All three are the same O(n·m) scan underneath, so this is not a performance choice. There are rfind and rindex for the last occurrence, and all of them take optional start and end bounds — which is how you find the second occurrence without slicing.
Step through it
What to watch
- All three scan the same way — the difference is only at the end.
-1is a valid index in Python, which is whyfindhas a sharp edge.if s.find(x):is a real bug — index 0 is falsy.
Say this out loud
"Same search, different failure. find gives -1, index raises, `in` gives a bool. If missing is normal I use find; if missing means something upstream is broken I use index so it fails loudly."