How to subtract a list from a list inPython?

It dawned on me today:  I’ll add lists on a regular basis (listC = listA + listB), but I don’t think I’ve ever ‘subtracted’ listA form listB.  A quick search didn’t come up with much (but I know it’s out there).  I came up with this method using list comprehensions:

listA = ["a","b"]
listB = ["b", "c"]
listC = [item for item in listB if item not in listA]
print listC
# ['c']

But there’s got to be an easier method?  Maybe using sets?

Posted on my Python Wiki too.

Centering joints in edge loops
New Processing Sketch Added: PerlinParticle03
  • Trackback are closed
  • Comments (4)
    • keir
    • March 2nd, 2009 2:59am

    Not sure on the speed, but this is how to do it with sets.

    listA = ["a","b"]
    listB = ["b", "c"]
    listC = list(set(listB).difference(listA))
    print listC
    # ['c']

    This style becomes more useful when you want to do intersections.

    listA = ["a","b"]
    listB = ["b", "c"]
    listC = list(set(listB). intersection(listA))
    print listC
    # ['b']

  1. Awesome, thanks. I have yet to get around to implementing any kind of usage of sets, but now that I have a good example…. 😉

    • Abdul Muneer
    • May 27th, 2011 6:19am

    But the set will have only unique elements. len(set) is always less than or equal to len (list). So be careful, u may lose some values.

    • Arvind
    • October 14th, 2018 7:19am

    Hi
    I have a list
    listA= [2.0, 2.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, 4.0, 7.0, 3.0, 8.0, 4.0, 2.0, [(4.0, 4.0)], (4.0, 7.0)], 4.0, 8.0, 1.0, 4.0, [(4.0, 7.0)], 5.0, 8.0]
    However remaining portion of my code expects above list as
    ListB=[2.0, 2.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, 4.0, 7.0, 3.0, 8.0, 4.0, 2.0, 4.0, 4.0, 4.0, 7.0, 4.0, 8.0, 1.0, 4.0, 4.0, 7.0, 5.0, 8.0]

    Basically I want to get rid of “[(” and “)]” from original listA.
    Can someone please help on this?

    Thanks
    AR

Comment are closed.