Learning Sets in Python Through Practical Examples

We have covered lists and dictionaries so far. Lists and dictionaries cover many cases, but sometimes you only care about whether a value exists, not where it appears or how many times it shows up. This is where sets become useful. A set is a collection of unique values with no guaranteed order.

Understanding the Core Idea of Sets

A set stores items without duplicates. If the same value is added more than once, Python keeps only one copy.
So sets are greate for removing duplicates, provided that the order of the items is not important.

Example of filtering duplicates with set


Sets are also great when you need to know if all items in a list are unique.

checking for duplicates with set


And if you want to ask about the common or unique values between two collections, you can use set operators. We are going to delve into this practice in a while.

So what makes sets stand out is that they do not support indexing. You cannot ask for the first or second element. Instead, you ask whether an element is present.

Creating Sets

You create a set using curly braces or the built in set() function.

Note: When you write empty curly braces like {}, Python will automatically generate a dictionary.
How to create a set

Methods for Sets

You can use the .add() method to include a new element in a set, simply by passing the element as an argument. If the element you’re trying to add is already present in the set, it won’t be added again
If you want to remove an element from a set, you can choose between two methods: .remove() or .discard(). Just pass the element you want to remove as an argument.
The .remove() method will throw a KeyError if the specified element is absent, whereas the .discard() method will simply do nothing.
We can remove all the elements from a set with the .clear() method.

Checking Membership Quickly

One of the most common uses of a set is membership testing. Checking whether a value exists in a set is fast and direct.

Checking whether a value exists in a set

This pattern appears often in validation logic and filtering tasks.

Working With Set Operations

Sets support operations that compare groups of values. You can find shared items or items that appear only in one group.

Example of set operations in action

The first result shows common elements. The second combines all unique elements.

Wrapping Up

Sets are designed to address a specific problem. When the order of elements is not a concern, sets provide a straightforward solution for checking duplicates.

Although my blog doesn’t support comments, feel free to reply via email or X.