w3resource

Python: Return the symmetric difference between two iterables, without filtering out duplicate values

Python List: Exercise - 242 with Solution

Write a Python program to get 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.

Sample Solution:

Python Code:

# Define a function 'symmetric_difference' that takes two lists, 'x' and 'y', as input.
def symmetric_difference(x, y):
    # Create sets '_x' and '_y' from the input lists 'x' and 'y'.
    _x, _y = set(x), set(y)
    
    # Calculate the symmetric difference of the two sets and store it in a list.
    # The symmetric difference contains elements that are unique to each set.
    symmetric_diff = [item for item in x if item not in _y] + [item for item in y if item not in _x]
    
    # Return the result.
    return symmetric_diff

# Call the 'symmetric_difference' function with two lists and print the symmetric difference.
print(symmetric_difference([10, 20, 30], [10, 20, 40])) 

Sample Output:

[30, 40]

Flowchart:

Flowchart: Return the symmetric difference between two iterables, without filtering out duplicate values.

Python Code Editor:

Previous: Write a Python program to create a dictionary with the unique values of a given list as keys and their frequencies as the values.
Next: Write a Python program to check if a given function returns True for every element in a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-242.php