RSS

Python, set’s awesomeness

14 Jul

So i have just learnt about sets. And I’m really impressed.
Example:

What is the best way to compare two lists?
Lets find all the unique items from list_a that are not in list_b.

First try

list_a = [1,2,3,4,5]
list_b = [4,5,6,7,8,9,0]

unique_list = []
for item_a in list_a:
if item_a not in list_b:
unique_list.append(item_a)

unique_list will contain [1,2,3]

2nd try

list_a = [1,2,3,4,5]
list_b = [4,5,6,7,8,9,0]
unique_list = [item_a for item_a in list_a if item_a not in list_b]

3rd try

set_a = set([1,2,3,4,5])
set_b = set([4,5,6,7,8,9,0])
unique_set = set_a.difference(set_b)

I like the 3rd try better. Nice, clean and neat.

This is just the tip, much more is possible with the set functionality.

More examples to come…

Advertisements
 
Leave a comment

Posted by on July 14, 2011 in Uncategorized

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: