Symmetric difference between two lists in Python

Find elements present in exactly one of two lists, preserving original order, with a simple Python function.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

22 lines
Python 3.9+
def symmetric_difference(list1, list2):
    """
    Return the symmetric difference of two lists.
    Elements present in exactly one of the lists, preserving order.
    """
    set1 = set(list1)
    set2 = set(list2)
    
    # Elements in list1 but not in list2
    diff1 = [x for x in list1 if x not in set2]
    # Elements in list2 but not in list1
    diff2 = [x for x in list2 if x not in set1]
    
    # Combine both differences
    return diff1 + diff2


if __name__ == "__main__":
    a = [1, 2, 3, 4, 5]
    b = [4, 5, 6, 7, 8]
    result = symmetric_difference(a, b)
    print(f"Symmetric difference of {a} and {b}: {result}")

Output

stdout
Symmetric difference of [1, 2, 3, 4, 5] and [4, 5, 6, 7, 8]: [1, 2, 3, 6, 7, 8]

How it works

This function converts each list to a set for O(1) membership checks, then uses list comprehensions to filter elements that appear in only one list. By checking each element against the opposite set, duplicates in the original lists are preserved. Combining both filtered lists gives the symmetric difference while maintaining the original order of each list.

Common mistakes

  • Using set(list1) ^ set(list2) directly, which loses order and drops duplicates
  • Forgetting to check membership against the opposite set, returning incorrect results
  • Modifying input lists in place while iterating over them

Variations

  1. Use set(list1) ^ set(list2) when order and duplicates don't matter
  2. Use list(set(list1).symmetric_difference(set(list2))) for unique elements only

Real-world use cases

  • Comparing user permissions between two roles to find permissions held by only one.
  • Identifying files changed in only one of two deployment environments.
  • Tracking items added or removed between two data snapshots during ETL reconciliation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.