What are the different data types of set items in Python?

Overview

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.

Data types of set items

A set can be of any data type: a string, int, or the boolean data types.

Example 1

In the code below, we will create sets of different data types and print them.

Code

# creating a string data type items of set
stringset = {"USA", "CANADA", "BRAZIL"}
# creating an integer data type items of set
intset = {1, 2, 3, 4, 5}
# crating a boolean data type items of set
boolset = {True, False, False}
# printing our sets
print(stringset)
print(intset)
print(boolset)

Code explanation

  • Line 2: We create a set with items of string data type.
  • Line 5: We create a set with items of integer data type.
  • Line 7: We create a set with items of Boolean data type.
  • Lines 11-13: We print these sets.

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.

Example 2

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 types
myset = {"abc", 34, True, 40, "male", "Hello", 20, "False"}
# printing the set
print(myset)

Code explanation

  • Line 2: We create a set with items of different data types in it.
  • Line 5: We print the set.

Free Resources