Back to Blog
Python

Python find vs index: Key Differences

python find vs index: Compare Python's find() and index() methods for strings and lists, and learn when each is appropriate based on error handling and return behavior.

pythonstring methodslist methodserror handlingsearch behavior
Illustration comparing Python's find and index methods with a magnifying glass over a string and a list, showing -1 and an error symbol.

When searching for a substring in a string or an element in a list, Python offers two similar-sounding methods: find() and index(). The python find vs index decision comes down to how each method signals that the target was not found. str.find() returns -1, while list.index() and str.index() raise a ValueError. That difference changes how you structure control flow and error handling.

What find() and index() Actually Do

Both methods search for a value and return the lowest index where it occurs. For strings, str.find(sub) returns the starting index of the first occurrence of sub. For lists, list.index(element) returns the index of the first occurrence of element. The search is left-to-right, and both accept an optional start and end range.

text = "hello world" print(text.find("world")) # 6 items = ["apple", "banana", "cherry"] print(items.index("banana")) # 1

The syntax is nearly identical, but the return behavior on failure is not.

The Critical Difference: Return Value vs Exception

str.find() returns -1 when the substring is not present. This makes it safe to use in conditional expressions without wrapping in a try block.

if text.find("missing") != -1: print("found") else: print("not found")

In contrast, both str.index() and list.index() raise a ValueError when the target is absent. You must catch that exception or guarantee the value exists beforehand.

items = [1, 2, 3] try: position = items.index(4) except ValueError: position = -1

This is the core distinction: find() is designed for optional search, while index() is designed for required membership.

Using str.find() for Optional Substring Search

When you need to check whether a substring exists and possibly extract the surrounding text, str.find() avoids exception handling. It is common in parsing scripts, log analysis, and configuration file processing where a key may or may not be present.

line = "level=info msg=started" pos = line.find("msg=") if pos != -1: message = line[pos + 4:] print(message)

Because find() returns a valid index or -1, you can use it directly in arithmetic and slicing without worrying about exceptions. This keeps the code linear and readable.

Using list.index() When the Element Must Exist

list.index() is appropriate when the element is expected to be in the list, and its absence indicates a bug or an invariant violation. Raising an exception makes the failure explicit rather than silently returning a sentinel.

priority = {"low": 1, "medium": 2, "high": 3} labels = ["low", "medium", "high"] # The label must be valid; an invalid label should fail loudly. label = "medium" rank = labels.index(label)

If the element is not guaranteed to exist, you have two options: check membership first with in, or catch the ValueError. The in check adds an extra pass over the list, which matters for large collections.

if target in items: idx = items.index(target) else: idx = -1

For lists, str.find() has no direct equivalent; you must use index() or a manual loop.

Performance and Runtime Behavior

Both find() and index() perform a linear scan in the worst case. For strings, the underlying algorithm is optimized in C, but it still examines characters until a match is found. For lists, index() compares elements using ==, which may invoke custom __eq__ methods on objects.

The practical performance difference between find() and index() is negligible. The real cost is the error handling pattern. Using try/except is cheap when the exception is not raised, but raising and catching an exception is significantly slower than returning a sentinel. If you expect the search to fail often, str.find() avoids exception overhead. For lists, checking in before index() doubles the scan cost; catching ValueError is faster when the element is usually present.

Memory usage is identical because both methods operate in place without creating new structures.

Common Mistakes and Edge Cases

One common mistake is using str.index() without a try block when the substring might be missing. This crashes the program with an unhandled ValueError. Another is confusing the return value of find() with a boolean: if text.find("x"): fails when the index is 0, because 0 is falsy. Always compare against -1 explicitly.

For lists, a frequent error is assuming index() returns the position of all occurrences. It returns only the first. If you need all positions, you must iterate with enumerate() or use a list comprehension.

positions = [i for i, v in enumerate(items) if v == target]

Also note that str.find() works only on strings, not on lists. If you need to search a list for a substring within its string elements, you must write a loop.

Choosing the Right Method for Your Code

The decision between find() and index() should be driven by whether the missing value is an expected condition or an error.

Use str.find() when the substring may legitimately be absent and you want to handle that case inline. It is ideal for parsing user input, configuration files, or any text where a key is optional.

Use list.index() (or str.index()) when the value must exist and its absence indicates a programming error or corrupted data. The exception will surface the problem early, making debugging easier.

For lists where the element might be missing, prefer catching ValueError over a separate in check when the list is large and the element is usually present. If the list is small or the search is rare, either approach is fine.

There is no universal "better" method. The right choice depends on how you want the absence of a value to affect the flow of your program. find() gives you a sentinel; index() gives you an exception. Both are valid tools, and knowing which one to reach for keeps your code predictable and maintainable.

python find vs index: Practical Usage and Code Examples | RYUSLOG DEV