1

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?

Tue
  • 371
  • 1
  • 14
  • 6
    It will be faster to store `list_of_ids` as `set_of_ids = set(list_of_ids)`. Sets are optimized for membership lookup. – AKX Feb 01 '22 at 18:50
  • I'm a bit ashamed I didn't think of that. That makes perfect sense. Thank you! – Tue Feb 01 '22 at 18:51
  • @bereal I meant there was no way of doing the if "id in bisect(list_of_ids)" or something similar. But as suggested by AKX, the set solution is clearly the elegant solution in this case. – Tue Feb 01 '22 at 18:53
  • @Tue ok, I see now that you don't change the list often, then it makes sense. – bereal Feb 01 '22 at 18:54

1 Answers1

1

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.

gilf0yle
  • 1,092
  • 3
  • 9