This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author marcospb19
Recipients marcospb19
Date 2020-05-06.13:49:00
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1588772940.44.0.121672930635.issue40531@roundup.psfhosted.org>
In-reply-to
Content
"""
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
History
Date User Action Args
2020-05-06 13:49:00marcospb19setrecipients: + marcospb19
2020-05-06 13:49:00marcospb19setmessageid: <1588772940.44.0.121672930635.issue40531@roundup.psfhosted.org>
2020-05-06 13:49:00marcospb19linkissue40531 messages
2020-05-06 13:49:00marcospb19create