Languages
[Edit]
EN

Python - lists intersection, difference, union and symmetric difference practical examples

3 points
Created by:
marc_so
1164

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:

def difference(input_list1, input_list2):
    return list(set(input_list1) - set(input_list2))


def symmetric_difference(input_list1, input_list2):
    return list(set(input_list1) ^ set(input_list2))


def intersection(input_list1, input_list2):
    return [item for item in input_list1 if item in input_list2]


def union(input_list1, input_list2):
    return list(set(input_list1) | set(input_list2))


# Usage example:

list1 = [1, 2, 3, 4]
list2 = [1, 2, 5, 6]

# Warning: the order matters!
print(difference(list1, list2))  # [3, 4]
print(difference(list2, list1))  # [5, 6]

print(symmetric_difference(list1, list2))  # [3, 4, 5, 6]
print(intersection(list1, list2))          # [1, 2]
print(union(list2, list1))                 # [1, 2, 3, 4, 5, 6]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join