[Python-3000] Python-3000 Digest, Vol 2, Issue 151

Guido van Rossum guido at python.org
Thu Apr 27 06:26:40 CEST 2006


On 4/26/06, Antoine Pitrou <solipsis at pitrou.net> wrote:
> 1) sets are most often built dynamically rather than statically (in my
> own experience)

The same is true to the same extent for lists and dicts.

And yet there are many uses for list and dict literals.

I've seen a lot of list and tuple literals that should have been sets,
because the main usage was to test whether some value was "in" the
list/tuple or not. That's an O(N) operation -- fortunately it's pretty
fast for tiny N.

> 2) set([1,2,3]) makes little sense anyway, since it probably isn't
> significantly more efficient than [1,2,3]

Here's a benchmark:

guido at pythonic:guido$ python2.4 -m timeit -s 'x = (1,2,3)' '(4 in x)'
1000000 loops, best of 3: 0.243 usec per loop
guido at pythonic:guido$ python2.4 -m timeit -s 'x = set((1,2,3))' '(4 in x)'
10000000 loops, best of 3: 0.147 usec per loop

The tuple version is slightly faster for (1 in x); but it's slower for
(2 in x), slower still for (3 in x). You can easily extrapolate from
this.

> The real benefit of sets is when you have at least tens or hundreds of
> elements; in that case you won't use a literal to build the set.

Have a look at keyword.py in the stdlib.

> Another remark is that I often use sets to hold my own objects rather
> than simple values (ints or strings). In a sense, I use sets as iterable
> containers where arbitrary remove() is fast.

Sure. That's not an argument against set literals.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list