DEV Community

Cover image for Python Sets – Understanding Sets in Python
Megalraja
Megalraja

Posted on

Python Sets – Understanding Sets in Python

When working with Python, we often need to store multiple values in a single variable. Python provides different collection data types, such as Lists, Tuples, Dictionaries, and Sets.

In this blog, let's understand Sets in Python, why we use them, and how to perform different operations.

1. What is a Set in Python?

A Set is a built-in collection data type in Python that stores multiple values in a single variable.

The main characteristics of a Set are:

  • Unordered: Elements do not have a fixed position.
  • Unchangeable elements: You cannot modify an individual element, but you can add or remove elements.
  • No duplicates: A Set automatically removes duplicate values.
  • Mutable: You can add or remove elements after creating a Set.

2. How to Create a Set

We use curly braces {} to create a Set.

numbers = {10, 20, 30, 40}

print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

{40, 10, 20, 30}
Enter fullscreen mode Exit fullscreen mode

Remember: Sets are unordered, so the output order may be different.

3. Creating an Empty Set

There is something important to remember when creating an empty Set.

a = {}

print(type(a))
Enter fullscreen mode Exit fullscreen mode

Output:

<class 'dict'>
Enter fullscreen mode Exit fullscreen mode

Why? Because {} creates an empty dictionary, not an empty Set.

To create an empty Set, use set().

a = set()

print(type(a))
Enter fullscreen mode Exit fullscreen mode

Output:

<class 'set'>
Enter fullscreen mode Exit fullscreen mode

4. Duplicate Values in Sets

One of the most useful features of Sets is that they do not allow duplicate values.

numbers = {10, 20, 30, 10, 20}

print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30}
Enter fullscreen mode Exit fullscreen mode

Python automatically removes duplicate values.

5. Adding Elements to a Set

We use the add() method to insert a single element.

numbers = {10, 20, 30}

numbers.add(40)

print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40}
Enter fullscreen mode Exit fullscreen mode

To add multiple elements, use update().

numbers.update([50, 60, 70])

print(numbers)
Enter fullscreen mode Exit fullscreen mode

6. Removing Elements from a Set

Python provides different methods to remove elements.

remove():

Removes an element. If the element does not exist, it raises a KeyError.

numbers = {10, 20, 30}

numbers.remove(20)

print(numbers)
Enter fullscreen mode Exit fullscreen mode

discard():

Removes an element without raising an error if it does not exist.

numbers.discard(50)

print(numbers)
Enter fullscreen mode Exit fullscreen mode

pop():

Removes and returns an arbitrary element.

numbers = {10, 20, 30}

numbers.pop()

print(numbers)
Enter fullscreen mode Exit fullscreen mode

clear():

Removes all elements from the Set.

numbers.clear()

print(numbers)
Enter fullscreen mode Exit fullscreen mode

7. Set Operations

Set operations are one of the most interesting features of Python Sets.

Let's understand them with examples.

Union ( | )

Combines elements from two Sets without duplicates.

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Intersection ( & )

Returns only the common elements.

print(a & b)
Enter fullscreen mode Exit fullscreen mode

Output:

{3}
Enter fullscreen mode Exit fullscreen mode

Difference ( - )

Returns elements that exist in the first Set but not in the second Set.

print(a - b)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2}
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference ( ^ )

Returns elements that are present in either Set, but not in both.

print(a ^ b)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2, 4, 5}
Enter fullscreen mode Exit fullscreen mode

8. Checking Elements in a Set

We can use the in and not in operators to check whether an element exists.

numbers = {10, 20, 30}

print(20 in numbers)
print(50 not in numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

True
True
Enter fullscreen mode Exit fullscreen mode

9. Frozen Sets

Python also provides a collection called frozenset.

A frozenset is an immutable version of a Set. Once created, you cannot add or remove its elements.

numbers = frozenset([10, 20, 30])

print(numbers)
Enter fullscreen mode Exit fullscreen mode

You cannot use methods like add() or remove() on a frozenset.

10. When Should We Use Sets?

Sets are useful in situations like:

  • Removing duplicate values from a list.
  • Finding common elements between two collections.
  • Comparing two groups of data.
  • Checking whether an element exists in a collection.
  • Performing mathematical set operations.

Example: Removing duplicates from a List

numbers = [10, 20, 10, 30, 20, 40]

unique_numbers = set(numbers)

print(unique_numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Python Sets are useful when we need to store unique values and perform operations such as Union, Intersection, Difference, and Symmetric Difference.

Top comments (0)