search

How to check if a variable is a set in Python?

To check if a variable is a set in Python, you can use the isinstance() function or compare the type of the variable to the set type. Here's an example:

# Using isinstance()
x = {1, 2, 3}
if isinstance(x, set):
    print("x is a set")
else:
    print("x is not a set")

# Using type()
y = [1, 2, 3]
if type(y) == set:
    print("y is a set")
else:
    print("y is not a set")

In the above example, the isinstance() function is used to check if the variable x is an instance of the set type. If it is, it prints "x is a set"; otherwise, it prints "x is not a set".

Similarly, the type() function is used to compare the type of the variable y with the set type. If they are equal, it prints "y is a set"; otherwise, it prints "y is not a set".

Keep in mind that both isinstance() and type() checks will only identify variables that are specifically of the set type. If you want to include other types that behave like sets, such as frozensets or other iterable objects, you can modify the checks accordingly. For example, you can use isinstance(x, (set, frozenset)) to check if the variable x is either a set or a frozenset.

Related Questions You Might Be Interested