In Python, what is the best way to compute the difference between two lists?
example
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
In Python, what is the best way to compute the difference between two lists?
example
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
Python 2.7.3 (default, Feb 27 2014, 19:58:35) - IPython 1.1.0 - timeit: (github gist)
Results:
@roman-bodnarchuk list comprehensions function def diff(a, b) seems to be faster.
In case of a list of dictionaries, the full list comprehension solution works while the
set
solution raisesTest Case
most simple way,
use set().difference(set())
answer is
set([1])
You can do a
and
One liner:
Or: