Distinct elements from multiple lists using set symmetric difference, as a tuple in Python


This Python code processes three lists, list1, list2, and list3, and creates a tuple named distinct_elements_symmetric_diff. The tuple contains the distinct elements that are present in exactly one of the three lists. Here's how the code works:

  • list1 = [1, 2, 3, 4]: This line initializes a variable named list1 and assigns it a list containing four integers.
  • list2 = [3, 4, 5, 6]: This line initializes a variable named list2 and assigns it another list containing four integers.
  • list3 = [5, 6, 7, 8]: This line initializes a variable named list3 and assigns it a third list containing four integers.
  • distinct_elements_symmetric_diff = tuple(set(list1) ^ set(list2) ^ set(list3)): This line initializes a variable named distinct_elements_symmetric_diff and assigns it a tuple created by applying the symmetric difference (^) operation on the sets of elements from list1, list2, and list3.
    • set(list1) ^ set(list2) ^ set(list3): This part of the code calculates the symmetric difference of the sets created from list1, list2, and list3. The symmetric difference includes elements that are unique to each set, i.e., elements that are present in exactly one of the three sets.
    • tuple(...): This surrounds the set and converts it back into a tuple.
  • print(list1): This line of code prints the original list1 to the console.
  • print(list2): This line of code prints the original list2 to the console.
  • print(list3): This line of code prints the original list3 to the console.
  • print(distinct_elements_symmetric_diff): This line of code prints the distinct_elements_symmetric_diff tuple to the console.

Source Code

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
list3 = [5, 6, 7, 8]
distinct_elements_symmetric_diff = tuple(set(list1) ^ set(list2) ^ set(list3))
print(list1)
print(list2)
print(list3)
print(distinct_elements_symmetric_diff)

Output

[1, 2, 3, 4]
[3, 4, 5, 6]
[5, 6, 7, 8]
(1, 2, 7, 8)

Example Programs