Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing one list from another

Tags:

python

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.

like image 216
dublintech Avatar asked Jan 29 '12 12:01

dublintech


3 Answers

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.

like image 121
Rob Wouters Avatar answered Nov 11 '22 07:11

Rob Wouters


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.

like image 39
Rafał Rawicki Avatar answered Nov 11 '22 07:11

Rafał Rawicki


I would try [x for x in a if a not in b].

like image 3
phimuemue Avatar answered Nov 11 '22 07:11

phimuemue