ChessMaster
ChessMaster

Reputation: 549

Python: Why Lists do not have a find method?

I was trying to write an answer to this question and was quite surprised to find out that there is no find method for lists, lists have only the index method (strings have find and index).

Can anyone tell me the rationale behind that? Why strings have both?

Upvotes: 16

Views: 21113

Answers (3)

metamatt
metamatt

Reputation: 14419

I think the rationale for not having separate 'find' and 'index' methods is they're not different enough. Both would return the same thing in the case the sought item exists in the list (this is true of the two string methods); they differ in case the sought item is not in the list/string; however you can trivially build either one of find/index from the other. If you're coming from other languages, it may seem bad manners to raise and catch exceptions for a non-error condition that you could easily test for, but in Python, it's often considered more pythonic to shoot first and ask questions later, er, to use exception handling instead of tests like this (example: Better to 'try' something and catch the exception or test if its possible first to avoid an exception?).

I don't think it's a good idea to build 'find' out of 'index' and 'in', like

if foo in my_list:
   foo_index = my_list.index(foo)
else:
    foo_index = -1 # or do whatever else you want

because both in and index will require an O(n) pass over the list.

Better to build 'find' out of 'index' and try/catch, like:

try:
    foo_index = my_list.index(foo)
catch ValueError:
    foo_index = -1 # or do whatever else you want

Now, as to why list was built this way (with only index), and string was built the other way (with separate index and find)... I can't say.

Upvotes: 4

Glenn Maynard
Glenn Maynard

Reputation: 57464

The "find" method for lists is index.

I do consider the inconsistency between string.find and list.index to be unfortunate, both in name and behavior: string.find returns -1 when no match is found, where list.index raises ValueError. This could have been designed more consistently. The only irreconcilable difference between these operations is that string.find searches for a string of items, where list.index searches for exactly one item (which, alone, doesn't justify using different names).

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342293

I don't know why or maybe is buried in some PEP somewhere, but i do know 2 very basic "find" method for lists, and they are array.index() and the in operator. You can always make use of these 2 to find your items. (Also, re module, etc)

Upvotes: 7

Related Questions