Skip to content

How to create a set in Python | Example code

  • by

You can create a set by using curly braces {} in Python. Just create a data type and assign the value using placing all the items (elements) inside curly braces {} and separated by a comma for multiple values.

Declare set

my_set = {"e1", "e2", "e2"}

empty_set = set()

Python set can contain any number of items and they may be of different types (integer, float, tuple, string, etc.)

Note: Mutable data types are now allowed in sets.

How to create a set in Python example

Simple example code sets written with curly brackets.

Note: Set elements are unordered, unchangeable, and do not allow duplicate values.

my_set = {1, 2, 3}

print(my_set)

print(type(my_set))

Output:

How to create a set in Python

To create an empty set you have to use the built-in method:

my_set = set()

Do comment if you have any doubts or suggestions on this Python set basics.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *