Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to get the data type of a set in Python

Onyejiaku Theophilus Chidalu

Overview

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.

Data types of set

A set can contain the following data types:

  1. String data type
  2. Integer data type
  3. Boolean data type
  4. A combination of the string, integer, or Boolean data types

It is worth noting that Python will always return <class 'set'> to let you know that what you created is a set.

Example

In the code below, we will create sets of items of the different data types mentioned above.

# 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}

# creating a set containing different data types
myset = {"abc", 34, True, 40, "male", "Hello", 20, "False"}


# printing our sets
print(stringset)
print(intset)
print(boolset)
print(myset)
Creating sets of different data types

Explanation

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.

Getting the data type of a set

To get the data type of a set, we make use of the type() function.

Syntax

type(set)

Parameter value

The type() function takes a single parameter value that represents the set.

Return value

The type() function will return the set data type, <class 'set'>.

Code

# creating a set
thisset = {"apple", "banana", "cherry"}

print(type(thisset))
Checking for data type

Note: Python will always define a set as objects with data type set. Hence, the output of the code above is <class 'set'>.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring