Search⌘ K

Set Theory Operations

Explore fundamental set theory operations in Python to work with unique elements in sets. Understand and apply union, intersection, difference, and symmetric difference to manipulate data efficiently and reinforce your knowledge through practical examples and exercises.

The mathematical definition of sets assigns some inherent properties to sets, such as element uniqueness and unorderedness. It also specifies the operations allowed, such as union, intersection, difference, and symmetric difference. Python supports all of these, as we’ll now see.

Unique elements

In Python, sets are used to store unique elements. Adding duplicate elements to a set will automatically remove the duplicates and only store one instance of each element. Let's see an example.

Python 3.10.4
# Creating a set with duplicate elements
elements = {1, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 9}
# Printing the set
print("Set with unique elements:", elements)

When you run this code, you'll see that the duplicate elements have been removed, and only unique ...