[Tutor] Sets in python

anil maran anilmrn at yahoo.com
Sun Jan 21 10:18:53 CET 2007


I think I don't really have to explain what a set is, as everyone should know them from mathematics. It's simply a pile of elements that do not have ordering and do not contain duplicates. 

A set has to be initialized with the elements of a list. Since you already know what a list is, we do this in one step. Just like with dictionaries, print can handle a set as it is.
Once we have a set, I show he first useful feature of sets: testing whether an element is in the set. 

inventory_carpenter=set(['helmet', 'gloves', 'hammer'])
print inventory_carpenter # outputs set(['helmet', 'hammer', 'gloves'])

print 'gloves' in inventory_carpenter # outputs 'True' 

Since sets are interesting only if we have more that one of them, let's introduce another one! Once we have that, we can immediately see what are the elements that both sets contain (intersection).

inventory_highscaler=set(['helmet', 'rope', 'harness', 'carabiner']) 

print inventory_carpenter & inventory_highscaler # outputs 'set(['helmet'])'

Similarly, we can have the union of sets ( using | ), difference ( using - ), or symmetric difference (using ^). 
For sets, you don't really need anything else, as you can do every meaningful operation using the ones above. For example, to add a new element, you can use union.

inventory_carpenter = inventory_carpenter | set(['nails']) 

Using the interpreter interactively

If you would like to try out the things you've learnt right now, you might appreciate that the interpreter can be used in an interactive way. In case you use it like that, you don't have to enter your commands to a file, then save and run it, just tell something to Python, and get the response immediately. All you have to do is to invoke the interpreter by typing 'python' to your shell.

kovacsp at centaur:~$ python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17)
[GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2\n
Type "help", "copyright", "credits" or "license" for more information.

Once you are here, you can just type anything you like, it will get interpreted immediately. The good new is that you don't even have to use print if you want to see the value of a variable, just type the name of it.\n

>>> a\u003d4
>>> a

\n\n",0] ); D(["ce"]);  //-->
All you have to do is to invoke the interpreter by typing 'python' to your shell.

Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070121/d44b1111/attachment.html 

More information about the Tutor mailing list