python tutorial

# Python Set

Python sets are just an unordered collection of items which does not allow duplicate elements. Python set is used when data structure needs to only have unique elements in it. Python sets also allow mathematical operations like `union``intersection`, and `difference` to find common and unique items between two sets.

## Using Sets in Python

Let’s dive into the Python set and understand how to use them as a data type. Below is an example that creates two sets as a wishlist of movies to watch for two different people. Sets are created using curly brackets. As you can see, Python sets do not allow duplicate values and will remove it automatically from a set.

Code Example
``````# movies to watch for john
john_movies_wishlist = {'Titanic', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Parasite', 'Die Hard'}
# movies to watch for adan
# note: duplicate items from a set are automatically removed
print(john_movies_wishlist)
{'Parasite', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Titanic'}
# note: items do not appear in the same order as written
{'Parasite', 'Gladiator', 'Psycho', 'The Lion King', 'Titanic', 'Coco'}``````

## Mathematical Operations on Python Sets

Let’s use common mathematical set operations like union, intersection and difference on our sets. Union will combine all the elements from both sets, intersection will provide all the elements present in both sets and difference will provide all the elements unique to each set.

Let’s do the following set operations on our movies wishlist for john and adam.

• Movies in John’s wishlist but not Adam’s – using `-` operator
• Movies in either John’s or Adam’s wishlist or in both of their wishlist – using `|` operator
• Movies in both John’s and Adam’s wishlist – using `&` operator
• Movies unique in John’s and Adam’s wishlist but not both – using `^` operator
Code Example
``````# movies to watch for john
john_movies_wishlist = {'Titanic', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Parasite', 'Die Hard'}
# movies to watch for adam
# note: duplicate items from a set are automatically removed
print(john_movies _wishlist)
{'Parasite', 'Titanic', 'Pulp Fiction', 'Forrest Gump', 'Die Hard'}
# note: items do not appear in the same order as written
{'Coco', 'Parasite', 'Gladiator', 'Titanic', 'The Lion King', 'Psycho'}
# movies in John’s wishlist but not Adam’s
{'Pulp Fiction', 'Die Hard', 'Forrest Gump'}
# movies in either John's wishlist or Adam's wishlist or in both wishlists
{'Coco', 'Parasite', 'Gladiator', 'Titanic', 'Pulp Fiction', 'The Lion King', 'Forrest Gump', 'Psycho', 'Die Hard'}
# movies in both John's wishlist and Adam's wishlist