List symmetric difference

OSCC · Python, List · Nov 2, 2020

Returns the symmetric difference between two iterables, without filtering out duplicate values.

• Create a set from each list.
• Use a list comprehension on each of them to only keep values not contained in the previously created set of the other.
def symmetric_difference(a, b):
(_a, _b) = (set(a), set(b))
return [item for item in a if item not in _b] + [item for item in b
if item not in _a]
symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]

Would you like to help us improve 30 seconds of code?

Recommended snippets

• List difference

Python, List

Calculates the difference between two iterables, without filtering duplicate values.

• List symmetric difference based on function

Python, List

Returns the symmetric difference between two lists, after applying the provided function to each list element of both.

• Bifurcate list based on function

Python, List

Splits values into two groups, based on the result of the given filtering function.