User12547645
User12547645

Reputation: 8437

Is there a save way to retrieve the index of a list without try catch?

I would like to know if there is a save and fast way of retrieving the index of an element in a list in python 3.

Idea:

# how I do it 
try:
    test_index = [1,2,3].index(4) # error
except:
    # handle error


# how I would like to do it: 
test_index = [1,2,3].awesome_index(4) # test_index = -1
if test_index == -1: 
    # handle error

The reason, why I would like to not use try, except is because try-except appears to be a little bit slower that an if-statement. Since I am handling a lot of data, performance is important to me.

Yes, I know that I could implement awesome_index by simply looping through the list, but I assume that there already is a function doing exactly that in a very efficient way.

Upvotes: 1

Views: 47

Answers (1)

Bharel
Bharel

Reputation: 26901

There is no such thing, but I like your thinking, so let's built upon it:

If you have only one index, and create many queries against it, why not maintain a set() or a dict() right next to that index?

numbers = [1,2,3]
unique_nunbers = set(numbers)

if 4 in unique_nunbers:
  return numbers.index(4)

Dict option:

numbers = [1,2,3]
unique_nunbers = dict(zip(numbers, range(len(numbers))))

index = unique_nunbers.get(4)
if index is None:
    # Do stuff

Lookups inside sets and dicts O(1), thus 4 in unique_numbers costs almost nothing. Iterating over the whole list in case something doesn't exist though, is a wasted O(n) operation.

This way, you have a way more efficient code, with a better algorithm, and no excepctions!

Keep in mind the same thing cannot be said for 4 in numbers, as it iterates over the whole list.

Upvotes: 1

Related Questions