-3

If I want to find the array index of a given item i Python, I'll do something like this:

a = ["boo", "foo", "bar", "foz"]
i = a.index("foo")

and i would be 1

If I'm looking for a non existing item a ValueError exception is raised.

Question: Why is it preferable to raise an exception instead of returning -1 (as JavaScript's equivalent function indexOf does)? I find it much easier to check for -1 instead of wrapping code blocks in try-catch.

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • 4
    because index in pyton can be reversed, `-1` mean the last one – Netwave Dec 15 '16 at 09:23
  • "Why does a function use two different mechanisms to return a result and to report an error?" – Because that's *sane*. – deceze Dec 15 '16 at 09:25
  • Implementing the same functionality is trivial. `def indexOf(needle, haystack): try: return hackstack.index(needle) except: return -1` I wouldn't do this for the aforementioned reasons of negative indexing in Python. – erip Dec 15 '16 at 09:26
  • Please **DON'T** vote to delete this question, it's a valid question. If you already know the answer, it doesn't mean it should be deleted! – Maroun Dec 15 '16 at 09:36

2 Answers2

3

Apart from the index reversal argument that Daniel already mentioned in his answer, you have to keep in mind that exceptions are a much more central concept in Python compared to JavaScript.

The idea of returning some special value, in this case -1 when not finding the value, is a concept that comes from the time when exceptions were not really a well made concept in languages. Most notably, it comes from C where special return values can mean all kinds of things.

JavaScript borrows much of this, as it also has no safe way of exception handling. Since it’s a weakly typed language, it can only catch all exception types, so just catching some IndexNotFoundException would not really work there.

In Python however, exceptions are a core concept of the language, and they are used all over the place for lots of exceptional things. So it makes sense to use them here for the case when an item is not in a list too.

Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602
1

Indexes in python can be reversed, -1 means last one:

a = ["boo", "foo", "bar", "foz"]
a[-1] == "foz"
True
Netwave
  • 40,134
  • 6
  • 50
  • 93