[ACCEPTED]-Get difference from two lists in Python-python

Accepted answer
Score: 14

Short answer, yes: list(set(l1) - set(l2)), though this will not 7 keep order.

Long answer, no, since internally 6 the CPU will always iterate. Though if you 5 use set() that iteration will be done highly 4 optimized and will be much faster then your 3 list comprehension (not to mention that 2 checking for membership value in list is much faster with 1 sets then lists).

Score: 11

You can't do it without iteration. Even 6 if you call a single method, internally 5 that will iterate.

Your approach is fine 4 for a small list, but you could use this 3 approach instead for larger lists:

s2 = set(l2)
result = [i for i in l1 if not i in s2 ]

This will 2 be fast and will also preserve the original 1 order of the elements in l1.

Score: 3

If you don't care about the order of the 1 elements, you can use sets:

l1 = set([2, 3, 4, 5])
l2 = set([0, 1, 2, 3])
print l1 - l2


set([4, 5])
Score: 2

The conversion to sets is great when your 5 list elements can be converted to sets. Otherwise 4 you'll need something like Mark Byers' solution. If you have 3 large lists to compare you might not want 2 to pay the memory allocation overhead and 1 simplify his line to:

[l1.remove(m) for m in l1 if m in l2]
Score: 1

You can use use set_1.difference_update(set_2) for 1 in place difference:

>>sl1 = set([2, 3, 4, 5])
>>sl2 = set([0, 1, 2, 3])
set([4, 5])
Score: 1

You can do this simply as follows:

list( set(l1) - set(l2) )

This should 1 do the trick.

Score: 0

Convert them to sets and use the difference 1 operator:


answer = set(l1) - set(l2)
Score: 0

Using the built-in module set

>>> a = set([1,2,3,4,5])
>>> b = set([1,3,5])
>>> a.difference(b)
set([2, 4])

Another approach

>>> a = set([1,2,3,4,5])
>>> b = [1,3,5]
>>> a.difference(b)
set([2, 4])


Score: 0

Simply as it is programming, a simple task 3 can be done in a variety of ways. We can 2 use list comprehension methods like this 1 for exactly the same problem

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
ddd = ["apple", "banana", "mango"]

newlist = [x for x in fruits if x not in ddd]


More Related questions