1

I suspect this is historical but nothing in the docs explains it.

demo = 'zero', 'one', 'two'
a = demo.index('three')

will raise a ValueError.

dict()['three'] and demo[100]

raises KeyError, IndexError

I find IndexError more logical for list.index failing. You failed to find the index of the requested key.

Am I right? And they can't change it after all this time? Or is ValueError the right one for the failing list.index

I also notice LookupError has parents: KeyError, IndexError

but not AttributeError which is effectively a keyError from dict

2
  • demo typed as tuple not dict, please check your example and update the question. Commented Jan 2, 2022 at 12:36
  • demo is a tuple. dict() is a dict. Not sure what you're warning me about Commented Jan 2, 2022 at 12:42

1 Answer 1

4

The problem that raises ValueError here is that the value was not found in the list (or tuple, or whatever).
In your second example, the reason it's a KeyError or IndexError is because the key or index was not found in your search (in these cases you're searching for a key or index).
When running list.index(), you're searching for a value.
Thus, when it is not found, a ValueError is raised.

Sign up to request clarification or add additional context in comments.

1 Comment

That does indeed justify things; meaning the answer is I'm wrong to find IndexError more logical. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.