Get difference from two lists in Python
Short answer, yes: list(set(l1) - set(l2))
, though this will not keep order.
Long answer, no, since internally the CPU will always iterate. Though if you use set()
that iteration will be done highly optimized and will be much faster then your list comprehension (not to mention that checking for membership value in list
is much faster with sets then lists).
You can't do it without iteration. Even if you call a single method, internally that will iterate.
Your approach is fine for a small list, but you could use this approach instead for larger lists:
s2 = set(l2)
result = [i for i in l1 if not i in s2 ]
This will be fast and will also preserve the original order of the elements in l1.
If you don't care about the order of the elements, you can use sets:
l1 = set([2, 3, 4, 5])
l2 = set([0, 1, 2, 3])
print l1 - l2
prints
set([4, 5])
The conversion to sets is great when your list elements can be converted to sets. Otherwise you'll need something like Mark Byers' solution. If you have large lists to compare you might not want to pay the memory allocation overhead and simplify his line to:
[l1.remove(m) for m in l1 if m in l2]
You can do this simply as follows:
list( set(l1) - set(l2) )
This should do the trick.