Python Program to Calculate the Symmetric Difference Between Two Lists
As a developer, you might come across a situation where you need to perform an operation that involves lists. In Python, two common operations you might want to perform are finding the union and intersection of two lists. However, in some cases, you may need to calculate the symmetric difference between two lists.
The symmetric difference between two lists is simply a list of elements that are in one of the lists but not in both. In Python, you can easily achieve this by using the symmetric_difference()
method. This method is built-in, so you do not need to install any additional packages or libraries.
To start, let’s create two lists, list1
and list2
, that we can use to demonstrate how to calculate the symmetric difference between them:
list1 = [1, 2, 3, 4]
list2 = [2, 3, 5, 6]
In this example, we have two lists, list1
and list2
. list1
contains the elements 1, 2, 3,
and 4
, while list2
contains the elements 2, 3, 5,
and 6
.
To calculate the symmetric difference between the two lists, we can use the symmetric_difference()
method:
sym_diff = set(list1).symmetric_difference(set(list2))
In this line of code, we first convert the two lists to sets using the built-in set()
function. We can then use the symmetric_difference()
method to find the elements that are not in both sets. The result is stored in the sym_diff
variable.
Now, let’s print out the result to see what we get:
print(sym_diff)
This will output the following:
{1, 4, 5, 6}
As you can see, the result is a set containing the elements 1, 4, 5,
and 6
. These are the elements that are in list1
or list2
, but not in both.
Conclusion
In conclusion, calculating the symmetric difference between two lists in Python is a simple operation that can be done using the built-in symmetric_difference()
method. By converting our lists to sets, we can easily find the elements that are not in both lists, and store the result in a variable for further use.