Skip navigation

One easy way to compare lists in python is to use Python Sets.


""" NOTES:
- requires Python 2.4 or greater
- elements of the lists must be hashable
- order of the original lists is not preserved
"""
def unique(a):
""" return the list with duplicate elements removed """
return list(set(a))

def intersect(a, b):
""" return the intersection of two lists """
return list(set(a) & set(b))

def union(a, b):
""" return the union of two lists """
return list(set(a) | set(b))

def difference(a, b):
""" show whats in list b which isn't in list a """
return list(set(b).difference(set(a)))

You can find differences, intersections, and unions of lists etc using sets.

Sets are not indexed.

Advertisements

3 Comments

    • Thiago Marcos P. Santos
    • Posted March 4, 2009 at 7:30 pm
    • Permalink
    • Reply

    Thanx! Help me a lot. I found that the truly difference between lists would be “symmetric_difference”.

    list1 = [1, 2, 3]
    list2 = [2, 3, 4]

    list(set(list1).symmetric_difference(set(list2)))
    [1, 4]

    list(set(list1).difference(set(list2)))
    [1]

    • I’m being pedantic here, but the “set difference”, i.e., the mathematical definition, is given by set.difference(). If you use set notation to describe it, here is the definition for two sets, A and B:

      Python: A.difference(B)
      Set notation: A – B

      Python: A.symmetric_difference(B)
      Set notation: (A – B) + (B – A)

      It’s just semantics, really; glad you found the one you needed.

  1. Hone, thanks for posting this insight. I wasn’t thinking about sets when I wanted the differences between 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

%d bloggers like this: