A set in Python is a collection of unordered and unchangeable items in a single variable. Sets are created or written inside curly braces {}
.
For example:
myset = {"USA", "CANADA", "BRAZIL"}
The variable myset
represents the set in the code above, while USA
, CANADA
, and BRAZIL
are the elements of the set.
A set can contain the following data types:
It is worth noting that Python will always return
<class 'set'>
to let you know that what you created is a set.
In the code below, we will create sets of items of the different data types mentioned above.
# creating a string data type items of setstringset = {"USA", "CANADA", "BRAZIL"}# creating an integer data type items of setintset = {1, 2, 3, 4, 5}# crating a boolean data type items of setboolset = {True, False, False}# creating a set containing different data typesmyset = {"abc", 34, True, 40, "male", "Hello", 20, "False"}# printing our setsprint(stringset)print(intset)print(boolset)print(myset)
In the code above, we create three sets, one each for a string, integer, and Boolean data type, and one with items of multiple data types.
To get the data type of a set, we make use of the type()
function.
type(set)
The type()
function takes a single parameter value that represents the set.
The type()
function will return the set data type, <class 'set'>
.
# creating a setthisset = {"apple", "banana", "cherry"}print(type(thisset))
Note: Python will always define a set as objects with data type
set
. Hence, the output of the code above is<class 'set'>
.