[Tutor] Sets are cool

Mike Hansen mhansen at cso.atmel.com
Wed Oct 27 16:27:42 CEST 2004


A while ago, I had to send an e-mail message to the users of two 
different applications. I didn't want duplicate e-mail addresses since I 
wasn't sure the mail server would send multiple messages. I found other 
ways to get the combined list, but it got me thinking on how would I do 
it using Python. Well, sets to the rescue!

 >>> from sets import Set

sets are new to version 2.3. I thought I had read that they might be 
built_in in 2.4. Anyone know?

 >>> mail_list = ["billyjoejeffbob at hick.com", "rakanishu at diabloii.com", 
"frodo at bagend.com", "averagejoe at ordinary.com", "rakanishu at diabloii.com"]

This first mail list above has rakanishu twice.

 >>> mail_list2 = ["averagejoe at ordinary.com", "wolverine at xmen.org", 
"id10t at clueless.net"]

mail_list2 has averagejoe in it. averagejoe is also in mail_list.

 >>> mail_list_set = Set(mail_list)

Convert mail_list to a set.

 >>> mail_list_set
Set(['billyjoejeffbob at hick.com', 'rakanishu at diabloii.com', 
'frodo at bagend.com', 'averagejoe at ordinary.com'])

Note: The double entry of rakanishu is now gone. Cool.

 >>> mail_list_set2 = Set(mail_list2)

Convert mail_list2 to a set.

 >>> combined_mail_list = mail_list_set.union(mail_list_set2)

union combines the two sets

 >>> combined_mail_list
Set(['billyjoejeffbob at hick.com', 'frodo at bagend.com', 
'averagejoe at ordinary.com', 'id10t at clueless.net', 
'rakanishu at diabloii.com', 'wolverine at xmen.org'])

Note: There is only one entry for averagejoe yet he was in both lists. Cool.
Mission accomplished.

I hadn't explored using sets in Python, and it's very handy. It looks 
like anytime you need to combine, find the differences, or find the 
common items in lists(or tuples), sets can make life easier.

There are ways of doing this without using sets, but IMHO, using sets 
might be easier to read than looping through lists and comparing items.

Thought I'd share another reason why I really love Python.

Mike



More information about the Tutor mailing list