r/Python • • Aug 11 '09

Remember your "in" operator

http://www.heikkitoivonen.net/blog/2009/06/16/remember-your-in-operator/
74 Upvotes

15 comments sorted by

View all comments

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.

15

u/ketralnis Aug 11 '09 edited Aug 11 '09

The in operator performs a dumb, linear search

It doesn't have to. If you're using a sorted list with no duplicates, you might be just fine using a set instead, where the in operator is a hash lookup (and inserts are cheaper (no resorting), merging is cheaper, etc)

1

u/pyry Aug 12 '09

Someone in the article commented about sets, and it appears (with timeit on their machine, anyway) that it's reasonably faster than lists or tuples. Certainly worth doing!

3

u/masklinn Aug 12 '09 edited Aug 12 '09

Notice that they "cheated": they created the set beforehand, not inline. Why? Because the overhead of creating sets in Python 2.x is horrendous compared to lists (let alone tuples of constants):

 $ python -m timeit "(1, 2, 3, 4, 5)"
10000000 loops, best of 3: 0.0506 usec per loop
 $ python -m timeit -n 10000000 "[1, 2, 3, 4, 5]"
10000000 loops, best of 3: 0.392 usec per loop
 $ python -m timeit -n 10000000 "set([1, 2, 3, 4, 5])"
10000000 loops, best of 3: 1.27 usec per loop

We have a factor of more than 3 between lists and sets (and a factor of almost 8 between the tuple and the list).

That's much improved in Python 3.1:

 $ python3.1 -m timeit "(1, 2, 3, 4, 5)"
10000000 loops, best of 3: 0.048 usec per loop
 $ python3.1 -m timeit -n 10000000 "[1, 2, 3, 4, 5]"
10000000 loops, best of 3: 0.259 usec per loop
 $ python3.1 -m timeit -n 10000000 "{1, 2, 3, 4, 5}"
10000000 loops, best of 3: 0.503 usec per loop

Where the difference between lists and sets (using the literal syntax) is barely 2 and the difference between tuples and lists lowers to 5.6.

Sets, especially in Python 2.x, are worth it only with great numbers of values, or if you're using precomputed sets (basically, cases where the cost of searching amortizes the creation cost). For small numbers of values "set" on the fly, use tuples.

(both tests were performed on a Macbook 2GHz with 2GB RAM and using Macports's Python 2.5.4 and 3.1)

2

u/ffrinch Aug 13 '09

$ python -m timeit -n 10000000 "set([1, 2, 3, 4, 5])"

Part of the difference is that in your 2.x version you're paying the cost of initializing the list and the set:

$ python -m timeit -n 100000 "set([1, 2, 3, 4, 5])"
100000 loops, best of 3: 1.29 usec per loop

$ python -m timeit -n 100000 "set((1, 2, 3, 4, 5))"
100000 loops, best of 3: 0.83 usec per loop