Python Tip #2: Difference of two Lists

A = [1,2,3,4,5,6,7]

B = [3,4,5,6,7,8,9,10]

Imagine that A is the results of a database call to see which numbers you have stored. Imagine B is a new list you want to insert in the database. However, you don’t want duplicates in. How to find which elements are in B and in A and take them out? Again, resorting to Sets, it comes down to one line:

print set.difference(set(B), set(A))

Careful with the order! If you call the arguments in the reverse order, it will reveal the elements of A not in B:

>>> print set.difference(set(A), set(B))
set([1, 2])
>>> print set.difference(set(B), set(A))
set([8, 9, 10])

One thought on “Python Tip #2: Difference of two Lists

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