# [Tutor] Sets

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Apr 18 16:58:01 2003

```On Fri, 18 Apr 2003, Magnus [iso-8859-1] Lyck=E5 wrote:

> That's a slightly terse explanation...
>
> >Not that I know a better implementation (I'm new to Python and only
> >recently began studying set theory), but why is using a dictionary a
> >good way to implement sets?  According to the set theory text I'm using
> >(and this is the text's notation, not Python code):
> >
> >     (1) {a, a} =3D {a}
> >     (2) {a, b} =3D {b, a}

Hello!

By the way, those two examples do work in Python.  We have to remember,
though, that Python's dictionaries don't exactly map to sets, since sets
don't have the "value" component.  To test out those two examples, let's
just use a proxy '1' as our value:

###
>>> {'a' : 1, 'a' : 1} =3D=3D {'a': 1}                 ## Example 1
1

>>> {'a' : 1, 'b' : 1} =3D=3D {'b' : 1, 'a' : 1}       ## Example 2
1

>>> {'a' : 1, 'b' : 1} =3D=3D {'b' : 1, 'c' : 1}       ## {a, b} !=3D {b, c=
}
0
###

The only thing is that dictionaries are a bit more fullly featured than
strict mathematical sets.  That is, we are only paying attention to the
'key' component of each key/value pair of a dictionary --- we're only
using dictionaries just for their set-like behavior with their keys.

That being said, Python 2.3 will have a 'sets' module:

http://www.python.org/doc/2.3a1/whatsnew/node2.html

so as soon as the new version of Python 2.3 comes out, we'll be able to
wholeheartedly suggest folks to use the 'sets' module.

The direction of the language, in the longer term, suggests that we'll
have built-in notation for defining sets that's much closer to the
notation in a math book.  Python Enhancement Proposal 218 describes what
this language extension might look like:

http://www.python.org/peps/pep-0218.html

So we have things to look forward to.  *grin* Until then, we can use
dictionaries as a tool for implementing sets.

Good luck!

```