{} for set notation

Carl Banks invalidemail at aerojockey.com
Fri Jul 14 16:07:38 EDT 2006


tac-tics wrote:
> Nick Vatamaniuc wrote:
> > I really like the set notation idea. Now that sets are first class
> > "citizens" along with dicts, lists and tuples I think they should be
> > used when it makes sense to use them
>
> In actual usage, though, how often is it strictly required one uses a
> set over a list?

A lot.  Perhaps you haven't personally encountered many use cases for
them, but I assure you that I and others have.

> It is similar to how queue and stack are not in the
> default namespace.

Not really.  set has proven itself to be more generally useful than the
other containers; that's why it was promoted to builtin only one
release after it was added to the standard library.  (IIRC, people on
this list were not very enthusiastic about it, since a dict could cover
some (not all) of the use cases, but it kind of won people over.)

> Unless you really need to ensure no one is allowed
> to make random access changes to your data, a list with push and pop is
> really all you need.

No it isn't.  There are several things sets are signifcantly better
than lists at:

1. A set ensures there are no duplicate items, which is often very
important.

2. Membership testing.  "a in b" is O(N) if b is a list, but O(1) if b
is a set.  What this means is, on average, testing whether an item is
in a list is roughly proportional to the length of the list, whereas
testing whether an item is in a set is roughly constant, no matter how
big the set it.  If you have thousands of items in your collection,
using a list is really going to slow things down.

3. Set operations: union, intersection, difference.  I use sets a lot,
but these operations not as often.  However, when the need for them
comes up, these methods are absolutely indispensable.

Again, maybe you don't encounter the need for them in your programming
(or perhaps you do and aren't aware of how sets could help), but many
people use them a lot.


Carl Banks




More information about the Python-list mailing list