2

I understand the working of the find and index methods -

str = "this is bad"
str.find("good")
-1
str.index("good")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

But what is the rationale behind having two functions for the same task?

I found this as a good answer and understood that with

find() - if the string isn't found, -1 that is returned is the same as the index of the last character in the string as so would create confusion

index() - the try-catch that would have to be used would create an overhead for a fast operation

or am I getting this wrong?

Also, why if that the case, the find() method can only be used with strings? Surely, the overhead using index() is the same whether you use it on lists or strings? Or is it because lists tend to be generally bigger in size than strings?

Community
  • 1
  • 1
qwertp
  • 839
  • 3
  • 11
  • 16
  • Yes, you have that right. As for your other question, see [here](http://stackoverflow.com/questions/3848954/python-why-lists-do-not-have-a-find-method). – TigerhawkT3 Jan 02 '16 at 03:11
  • Is there something in particular you didn't find satisfying about the answer you cite? I thought it was pretty good. (I can't answer your last question, however.) – one_observation Jan 02 '16 at 03:14
  • @TigerhawkT3 Could you point out in that question, what you think is the correct reason fo not having `find()` for lists? The most upvoted answer seems to give alternatives but not the reason.Thanks. – qwertp Jan 02 '16 at 03:19
  • @Sophologist No as I said, the answer was good and helped me understand the reason for `find()` to have been introduced later on.I cited it to ask why the same rationale wasn't being used for lists – qwertp Jan 02 '16 at 03:20
  • I'm not sure there _is_ a correct reason, as you can see from the other answers there. Sometimes a feature doesn't get implemented because it just doesn't seem necessary enough. Maybe a fast search for a possibly absent substring is a common use case for strings, but lists are generally searched for objects that are guaranteed to be present. I don't know. – TigerhawkT3 Jan 02 '16 at 03:22
  • Maybe the source code implementation was totally different so they didn't feel like giving same name for two different classes' methods ? – Rockybilly Jan 02 '16 at 04:05
  • @Rockybilly Ya looks like the answer is simple semantics rather than technical. Unless, someone has knows a technical reason. – qwertp Jan 02 '16 at 04:10

0 Answers0