EN
Python - lists intersection, difference, union and symmetric difference practical examples
3 points
In this article, we would like to show you how to implement instersection, difference, union and symmetric difference functions for lists in Python.
Practical example:
xxxxxxxxxx
1
def difference(input_list1, input_list2):
2
return list(set(input_list1) - set(input_list2))
3
4
5
def symmetric_difference(input_list1, input_list2):
6
return list(set(input_list1) ^ set(input_list2))
7
8
9
def intersection(input_list1, input_list2):
10
return [item for item in input_list1 if item in input_list2]
11
12
13
def union(input_list1, input_list2):
14
return list(set(input_list1) | set(input_list2))
15
16
17
# Usage example:
18
19
list1 = [1, 2, 3, 4]
20
list2 = [1, 2, 5, 6]
21
22
# Warning: the order matters!
23
print(difference(list1, list2)) # [3, 4]
24
print(difference(list2, list1)) # [5, 6]
25
26
print(symmetric_difference(list1, list2)) # [3, 4, 5, 6]
27
print(intersection(list1, list2)) # [1, 2]
28
print(union(list2, list1)) # [1, 2, 3, 4, 5, 6]