How to create a set in Python | Example code

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 and suggestions on this Python set basics.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.