The in operator performs a dumb, linear search, which is suboptimal for searching in sorted lists.
That is not exactly true. in delegates the search to __contains__.
And in the case of lists, well it makes sense to implement __contains__ as a "dumb, linear" search given Python has no guarantee the list is sorted, and sorting it beforehand would far exceed the performances of a basic O(n) linear search.
edit: ideally, you could compose a list with some kind of OrderedList container whose __contains__ would perform a bisection search, but if you got it wrong and your list isn't completely sorted, everything's going to break… so unless you have very strong guarantees that your sequence is sorted, linear search is one of the few "safe" options.
9
u/joshdick Aug 11 '09
This is a neat way to condense tedious conditionals, but be careful using it for other things.
The in operator performs a dumb, linear search, which is suboptimal for searching in sorted lists.
Maybe this is obvious to everyone else, but it really slowed me down while first learning the language.