New submission from João Marcos <[email protected]>:
"""
PROBLEM:
When trying to search the position of an element inside a list, we should use
the `in` operator to first check if the element exists, and then use the
`index` method to obtain the index.
`in` (__contains__) runs a linear search to return the boolean.
`index` also runs a linear search to return the index.
This makes the code slower, because we need to search for the same item twice.
FEATURE PROPOSAL:
Similar to str.find(), list.find() should be implemented, where -1 is returned
when the element isn't present
"""
# Since there's no list.find(), this is my workaround to achieve making only
one linear search per query
def find(container: list, index: int) -> int:
""" Str.find() behavior but for lists """
try:
return container.index(index)
except ValueError:
return -1
# Example driver code:
index = find(list, possible_element)
if index_of_element == -1:
pass # Not found
else:
pass # Found
----------
messages: 368254
nosy: João Marcos
priority: normal
severity: normal
status: open
title: Adding the method find() to list
type: enhancement
versions: Python 3.9
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue40531>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com