Symmetric difference between two lists in Python
Find elements present in exactly one of two lists, preserving original order, with a simple Python function.
Python code
22 linesdef 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
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
- Use set(list1) ^ set(list2) when order and duplicates don't matter
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.