How to remove common elements between two lists in python ?

Published: July 30, 2022

Updated: December 09, 2022

DMCA.com Protection Status

Examples of how to remove common elements between two lists in python

Create lists in python

Let's consider the following lists:

a = [1,1,2,3,4,5,6]

b = [2,4]

c = [2,4,7,8]

Remove common elements using the python ^ operator

To remove common elements between a and b lists, a solution is to use the python ^ operator:

list( set(a)^set(b) )

returns here

[1, 3, 5, 6]

and

list( set(a)^set(c) )

returns

[1, 3, 5, 6, 7, 8]

Note that with this approach duplicate elements are removed.

Remove common elements using a "list comprehension"

Another solution is to use intersection():

list( set(a).intersection(b) )

gives

[2, 4]

list( set(a).intersection(c) )

also gives

[2, 4]

with a "list comprehension":

new_a = [e for e in a if e not in list( set(a).intersection(b) )]
new_b = [e for e in b if e not in list( set(a).intersection(b) )]

print(new_a)
print(new_b)

gives

[1, 1, 3, 5, 6]
[]

To avoid creating new lists:

for e in a:
    if e in i:
        a.remove(e)

gives

[1, 1, 3, 5, 6]

Remove common elements using difference

Another solution:

list( set(a).difference(b) )

gives

[1, 3, 5, 6]

Same as

list( set(a) - set(b) )

gives

[1, 3, 5, 6]

Check if a list is a subset of another list

Note: there are different approaches to remove common elements between two lists. It might be useful to check first if one list is a subset of another:

set(b).issubset(set(a))

here it will give:

True

while

set(c).issubset(set(a))

returns:

False