[New-bugs-announce] [issue45271] Add a 'find' method (a'la str) to list

Dávid Nemeskey report at bugs.python.org
Thu Sep 23 11:05:06 EDT 2021


New submission from Dávid Nemeskey <nemeskeyd at gmail.com>:

There is an unjustified asymmetry between `str` and `list`, as far as lookup goes. Both have an `index()` method that returns the first index of a value, or raises a `ValueError` if it doesn't exist. However, only `str` has the `find` method, which returns -1 if the value is not in the string.

I think it would make sense to add `find` to `list` as well. For starters, it would make the API between the two sequence types more consistent. More importantly (though it depends on the use-case), `find` is usually more convenient than `index`, as one doesn't have to worry about handling an exception. As a bonus, since `list` is mutable, it allows one to write code such as

    if (idx := lst.find(value)) == -1:
        lst.append(value)
    call_some_function(lst[idx])

, making the method even more useful as it is in `str`.

----------
messages: 402497
nosy: nemeskeyd
priority: normal
severity: normal
status: open
title: Add a 'find' method (a'la str) to list

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45271>
_______________________________________


More information about the New-bugs-announce mailing list