search

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

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

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

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

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

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

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

Related Questions You Might Be Interested