Understanding Python Sets: The Key to Managing Unique Data

Dr. Soumen Atta, Ph.D.
5 min readApr 1, 2023
Photo by Dean Pugh on Unsplash

A set in Python is an unordered collection of unique elements. The elements can be of any data type, including numbers, strings, and tuples. In this tutorial, we’ll cover the basics of creating and manipulating sets in Python.

Creating a Set

You can create a set in Python using curly braces ({}) or the built-in set() function. Here's an example:

# Using curly braces
my_set = {'apple', 'banana', 'orange'}

# Using the set() function
my_set = set(['apple', 'banana', 'orange'])

Note that when using the set() function, you need to pass in an iterable object (e.g. list, tuple, string). Also, if you try to create a set with duplicate elements, only the unique elements will be stored in the set.

Adding Elements to a Set

You can add elements to a set using the add() method. Here's an example:

my_set = {'apple', 'banana', 'orange'}
my_set.add('grape')
print(my_set)

--

--

Dr. Soumen Atta, Ph.D.

I am a Postdoctoral Researcher at the Faculty of IT, University of Jyväskylä, Finland. You can find more about me on my homepage: https://www.soumenatta.com/