Language: EN

python-sets

Sets in Python

Sets, or sets, are data structures that allow us to store collections of unique and unordered elements.

This means that there can be no duplicates in a set and the elements are not ordered by position.

Characteristics of sets:

  • Unique Elements: Sets cannot contain duplicate elements, so each element is unique.
  • Unordered: The elements in a set do not have a specific order, and there is no guarantee that the order in which they were added will be maintained.

Creating sets

Sets in Python can be created using curly braces {}.

In this case, the elements are listed separated by commas within the braces to initialize the set.

my_set = {1, 2, 3}

Create a set with the set() function

It is also possible to create sets using the set() function. A list is passed as an argument to the set() function, and the function creates a set with the elements from that list.

my_other_set = set([1, 2, 3])

For example, here we have created a Set {1, 2, 3} from a List that contained [1, 2, 3].

Operations with sets

Adding elements

Sets in Python have the add() method that is used to add a single element to the set.

my_set.add(6)  # Adds the element 6 to the set

Removing elements

Sets in Python have the remove() method that is used to remove a specific element from the set.

Additionally, the discard() method can also be used to remove an element, but it will not throw an error if the element is not present in the set.

my_set.remove(3)  # Removes the element 3 from the set
my_set.discard(2)  # Removes the element 2 if it is present

Union of sets

The union of sets can be performed using the union() method or the | operator. This creates a new set that contains all the elements from both original sets, eliminating duplicates.

union_set = my_set.union(my_other_set)  # Unites the two sets into a new one
union_set = my_set | my_other_set  # The same using the | operator

Intersection of sets

The intersection of sets can be performed using the intersection() method or the & operator. This creates a new set that contains only the elements that are present in both original sets.

intersection_set = my_set.intersection(my_other_set)  # Gets the intersection of the sets
intersection_set = my_set & my_other_set  # The same using the & operator

Difference of sets

The difference between sets can be calculated using the difference() method or the - operator. This creates a new set that contains only the elements that are present in the first set but not in the second.

difference_set = my_set.difference(my_other_set)  # Gets the difference between the sets
difference_set = my_set - my_other_set  # The same using the - operator

Practical examples