A set in Python is a collection of multiple unordered and unchangeable items in a single variable.
Sets are written using the curly braces {}
.
For example:
myset = {"USA", "CANADA", "BRAZIL"}
From the code above, the variable myset
represents the set while "USA"
, "CANADA"
, and "BRAZIL"
represent the items of the set.
A set can be of any data type: a string
, int
, or the boolean
data types.
In the code below, we will create sets of different data types and print them.
# 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}# printing our setsprint(stringset)print(intset)print(boolset)
As we can see, we are able to create sets having items of different data types by using the curly braces {}
.
Interestingly, the same set can also contain items of different data types.
In the code below, we will create a set that contains items of string, integer, and Boolean data types.
# creating a set with different data typesmyset = {"abc", 34, True, 40, "male", "Hello", 20, "False"}# printing the setprint(myset)