• author: Python and Pandas with Reuven Lerner

Exploring the Python Standard Library: Sets

Sets are one of the most powerful data structures in Python. They allow you to store unique elements in an unordered collection. Sets have a variety of applications in data analysis, web development, and scientific computing.

In this video series, Ruben Lerner explores the various functions and methods of the Python standard library for sets. Whether you're new to Python or an experienced developer, there's something in this series for you.

Creating Sets

Sets are similar to dictionaries in that they use curly braces to enclose their elements. However, unlike dictionaries, sets don't have values. Instead, they contain only unique keys.

To create a set, you can use curly braces, like this:

s = {10, 20, 30, 40, 50}

Alternatively, you can use the set() function and pass it an iterable, like a list or tuple:

s = set([10, 20, 30, 40, 50])

Both of these methods create the same set, but the first is considered more modern and efficient.

Adding Elements to Sets

Once you have a set, you can add elements to it using the add() method. For example:


If you try to add an element that's already in the set, nothing will happen. This is because sets can only contain unique elements.

You can also add multiple elements to a set at once using the update() method. This method takes an iterable as its argument and adds each element from the iterable to the set. For example:

to_add = [30, 40, 50, 60, 70, 80]

This adds all the elements from to_add to the set s. Again, duplicates are ignored.

Creating Empty Sets

To create an empty set, you can use the set() function with no arguments. For example:

s = set()

Trying to create an empty set with curly braces will result in a dictionary, not a set.

What Can You Put in a Set?

Sets can contain any hashable object, such as numbers, strings, and tuples (as long as the tuples contain only hashable objects). Sets cannot contain unhashable objects, such as lists.


Sets are a powerful data structure in Python with many use cases. This video series covers the basics of working with sets in Python, including creating sets, adding elements, and understanding what can be contained in a set. Follow along with the rest of the series to learn more about working with sets in Python. Have comments, questions, or other thoughts? Be sure to reach out and get in touch.

Previous Post

Exploring the Power of Byte Arrays in Python

Next Post

Modeling Commons: Sharing and Collaborating on NetLogo Models

About The auther

New Posts

Popular Post