Join two Sets in Python (Union, Intersection, Difference, Symmetric) - Python Tutorial for Beginners

preview_player
Показать описание
🎓 Welcome back to Digital Academy, the Complete Python Development Tutorial for Beginners, which will help you Learn Python from A to Z!

🖥️ How to Join two Sets in Python? (Union, Intersection, Difference, Symmetric)

Sets are commonly used for Computing Mathematical Operations in Python, such as intersection, union, difference, and symmetric difference. Consequently, there are multiple ways to join two sets in Python.

○ Union of two Sets in Python

Union of the sets A and B is the set of all items in either A or B. You can use the method union(), that returns a new set containing all items from both sets, or the method update(), that inserts all the items from one set into another set. You can perform union on 2 sets using the method union() in Python, or "|" operator.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.update(B)
my_new_set = (A | B)
my_new_set = A.union(B)
# my_new_set = {'blue', 'green', 'yellow', 'orange', 'red'}

There are other methods that joins two sets and keeps ONLY the duplicates or, on the opposite, NEVER keeps the duplicates...

○ Intersection of two Sets in Python

Intersection of the sets A and B is the set of items common to both A and B. And you can perform intersection on two sets using the method intersection() in Python, or "&" operator.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

my_new_set = (A & B)
my_new_set = A.intersection(B)
# my_new_set = {'red'}

○ Difference of two Sets in Python

Set Difference of A and B is the set of all items that are in A but not in B. You can compute the difference between two sets using the method difference(), or "-" operator.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

my_new_set = (A - B)
my_new_set = A.difference(B)
# my_new_set = {'blue', 'green'}

○ Symmetric Difference of two Sets in Python

Symmetric difference of sets A and B is the set of all elements in either A or B, but not both. You can compute symmetric difference between two sets using symmetric_difference() in Python, or "^" operator.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

my_new_set = (A ^ B)
my_new_set = A.symmetric_difference(B)
# my_new_set = {'orange', 'blue', 'green', 'yellow'}

Let's play this video, stick around and watch until the end of this video! 👍🏻

- Digital Academy™ 🎓

***

☞ WATCH NEXT:

#Python #Tutorial #Beginners #Shorts

***

♡ Thanks for watching and supporting ♡
Please Subscribe. Hit the notification bell.
Like, Comment and Share.

***

♡ FOLLOW US ♡

♡ SUPPORT US ♡

***
Рекомендации по теме
Комментарии
Автор

Your explained so well how to join sets on Python 👍🏻

chloejbt