Home » Data Science » Python » Python Sets

Newly Updated Posts

Python Sets

In this tutorial we will learn Sets in Python and its operation:

Python sets are unordered collections of unique elements. They are defined by enclosing a comma-separated sequence of values within curly braces ({}) or by using the built-in set() function.

Here’s an example of creating a set:

fruits = {"apple", "banana", "orange"}

In this example, the fruits set contains three elements: “apple”, “banana”, and “orange”. Notice that the order of the elements in a set is not guaranteed, and duplicates are automatically removed. If you print the set, the order of the elements may vary.

Sets have various operations and methods that can be performed on them. Some commonly used operations include:

1. Adding an element to a set:

fruits.add("mango")

2. Removing an element from a set:

fruits.remove("apple")

3. Checking if an element is present in a set:

if "banana" in fruits:
    print("Banana is in the set!")

4. Performing set operations like union, intersection, and difference:

set1 = {1, 2, 3}
set2 = {2, 3, 4}

union_set = set1 | set2  # union
intersection_set = set1 & set2  # intersection
difference_set = set1 - set2  # difference

print(union_set)            # {1, 2, 3, 4}
print(intersection_set)     # {2, 3}
print(difference_set)       # {1}

Sets are mutable, meaning you can add or remove elements from them. However, since sets are unordered, indexing and slicing operations are not supported. To iterate over the elements of a set, you can use a loop or convert it to a list.

Sets are often used when you need to store a collection of unique elements or perform operations such as finding common elements, removing duplicates, or checking membership efficiently.