In python (2.7) we can do:
>>> a = [1, 2, 3]
>>> b = [4 , 5]
>>> a + b
[1, 2, 3, 4, 5]
However we can't do a - b.
Since python seems to have something cool for nearly everything, what is the most python-esque to do a - b, in your opinion?
Similar question for dictionaries, which can neither do a + b, or a - b, where a and b are both dictionaries. Thanks.
You can do this with sets:
>>> s = set([1,2,3] + [4,5])
>>> s - set([4, 5])
{1, 2, 3}
The main difference of course being a set cannot contain duplicate elements.
I would do:
>>> a = [1, 2, 3]
>>> b = [2, 3]
>>> filter(lambda x: x not in b, a)
[1]
or using list comprehensions
[x for x in a if x not in b]
And it can be done the same way for dictionaries.
Set has defined operator -
and methods difference
and symmetric_difference
. If you are planning to make extensive use of that operations use set instead of list or dict.
I would try [x for x in a if a not in b]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With