Tue
Tue

Reputation: 432

Pythonic way of searching through a sorted list

I am looking for the most pythonic/elegant way of doing the following:

    if id in list_of_ids:
        #do something

where list_of_ids is a large ordered list. I will be doing this operation millions of times for different id, (but list_of_ids will remain the same).

I could use something like what is suggested here: Searching a sorted list? But none of those methods seem really elegant to implement in the above. Is there a nice way to inform python that it is doing the "string in list_of_strings" on an ordered list, maybe a simple keyword or something?

Upvotes: 1

Views: 66

Answers (1)

gilf0yle
gilf0yle

Reputation: 1102

Using a set or dictionary will make your search efficient as their looks ups are O(1), Though dictionary will cost you memory it is fast and without a mapping, dictionary is not recommended you can use set in this case.

Upvotes: 1

Related Questions