Open In App

Python | Check if variable is tuple

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we can have a problem in which we need to check if a variable is single or a record. This has applications in domains in which we need to restrict the type of data we work on. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well. 

Python3




# Python3 code to demonstrate working of
# Check if variable is tuple
# using type()
 
# initialize tuple
test_tup = (4, 5, 6)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Check if variable is tuple
# using type()
res = type(test_tup) is tuple
 
# printing result
print("Is variable tuple ? : " + str(res))


Output

The original tuple : (4, 5, 6)
Is variable tuple ? : True

The time complexity is constant time or O(1).

The auxiliary space is also constant or O(1). 

Method #2: Using instance() 

Yet another function that can be employed to perform this task. It also returns true, in case the parent class of variable(if exists) is a tuple. 

Python3




# Python3 code to demonstrate working of
# Check if variable is tuple
# using isinstance()
 
# initialize tuple
test_tup = (4, 5, 6)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Check if variable is tuple
# using isinstance()
res = isinstance(test_tup, tuple)
 
# printing result
print("Is variable tuple ? : " + str(res))


Output

The original tuple : (4, 5, 6)
Is variable tuple ? : True

The time complexity is O(1)

The auxiliary space is also O(1)

Method 3: Using list comprehension 

Python3




test_tup = (4, 5, 6)
x=["true" if type(test_tup)==tuple else "false"]
print(x)


Output

['true']

Method 4: Using __class__
 

Python3




#initialize tuple
test_tup = (4, 5, 6)
 
#printing original tuple
print("The original tuple : " + str(test_tup))
 
#Check if variable is tuple
# class
res = test_tup.__class__==tuple
 
#printing result
print("Is variable tuple ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original tuple : (4, 5, 6)
Is variable tuple ? : True

Time Complexity: O(1)
Auxiliary Space: O(1)
Explanation:
In this approach, the class attribute of the variable is used to check if it belongs to the tuple class.
If the class attribute is equal to the tuple class, it returns True, otherwise, it returns False.
This approach is simple and efficient with a time complexity of O(1).

Method 5: “indexing and length check”

This approach tries to access the first element of the variable (i.e., ‘var[0]’) and also checks if the variable has a defined length (i.e.,’ len(var)’). If both of these operations can be performed without raising a ‘TypeError’ or ‘IndexError’, then the variable is assumed to be a tuple and the function returns ‘True’. If either of these operations raises an error, then the variable is assumed not to be a tuple and the function returns ‘False’.

In this example, we define the ‘is_tuple’ function and then call it with three different arguments: a tuple ‘x’, a list ‘y’, and a string ‘z’. The function correctly identifies ‘x’ as a tuple and ‘y’ and ‘z’ as not tuples, and returns ‘True’ or ‘False’ accordingly. The ‘print’ statements are used to display the output of the function.

Python3




def is_tuple(var):
    try:
        # Check if the variable can be indexed
        var[0]
        # Check if the variable has a defined length
        len(var)
        # If both conditions are met, assume the variable is a tuple
        return True
    except (TypeError, IndexError):
        # If the variable cannot be indexed or does not have a defined length,
        # assume it is not a tuple
        return False
 
# Call the function with an argument
x = (1, 2, 3)
print(is_tuple(x))  # Output: True
 
y = [1, 2, 3]
print(is_tuple(y))  # Output: False
 
z = 'hello'
print(is_tuple(z))  # Output: False


Output

True
True
True

 Time complexity: O(1)

Auxiliary space: O(1)

Method 6: “Iterative Check for Tuple”

This approach assumes that tuples are iterable and other types are not.

Here are the steps to implement this approach:

  1. Define a function that takes a single argument, the variable to be checked.
  2. Attempt to iterate over the variable using a for a loop.
  3. If the loop completes without raising a TypeError, return True to indicate that the variable is a tuple.
  4. If a TypeError is raised during iteration, catch the exception and return False to indicate that the variable is not a tuple.
     

Python3




def is_tuple(variable):
    try:
        for _ in variable:
            pass
        return True
    except TypeError:
        return False
 
# Examples
print(is_tuple((1, 2, 3))) 
print(is_tuple(("a", "b", "c"))) 
print(is_tuple([1, 2, 3]))
print(is_tuple("hello")) 
print(is_tuple(123))


Output

True
True
True
True
False

The time complexity of this approach is O(n)

The auxiliary space is O(1)

Approach: element access or subscripting

Here are the steps for the “element access” or “subscripting” approach to checking if a variable is a tuple:

  1. Try to access an element of the variable at index 0 using square brackets: x[0].
  2. If no exception is raised, assume that the variable is a non-empty tuple.
  3. If a TypeError exception is raised, assume that the variable is not subscriptable (and therefore not a tuple).
  4. If an IndexError exception is raised, assume that the variable is empty (and therefore could be a tuple, but we cannot say for sure).
  5. Optionally, you can catch other exceptions to handle cases where x is not iterable or has a custom __getitem__ method that does not behave like a tuple.
  6. Return True if the variable is a tuple and False otherwise.

Python3




def is_tuple(obj):
    if hasattr(obj, '__getitem__') and hasattr(obj, '__iter__'):
        return all(hasattr(obj, attr) for attr in ('count', 'index'))
    return False
 
 
# Example usage
t = (1, 2, 3)
l = [1, 2, 3]
s = '123'
 
print(is_tuple(t))
print(is_tuple(l))
print(is_tuple(s))


Output

True
True
True

The time complexity approach is O(1),

The auxiliary space complexity of the function is also O(1)

Approach: Tuple Unpacking Check

Tuple unpacking can be used to check if a variable is a tuple. If the variable is a tuple, then the unpacking will succeed, otherwise, it will raise a TypeError.

Steps:

  1. Use try-except block to catch TypeError raised by tuple unpacking.
  2. If the unpacking succeeds, then the variable is a tuple.

Python3




def is_tuple(my_var):
    try:
        a, b, c = my_var
        return True
    except TypeError:
        return False
 
 
# Example usage
t = (1, 2, 3)
l = [1, 2, 3]
s = '123'
 
print(is_tuple(t))
print(is_tuple(l))
print(is_tuple(s))


Output

True
True
True

Time Complexity: The time complexity of this approach is O(1)
Auxiliary Space: The auxiliary space used in this approach is O(1)

Duck Typing Check

Steps:

  1. Check if the input variable has the attributes or methods typically associated with a tuple.
  2. Return True if the variable behaves like a tuple, otherwise return False.

Python3




def is_tuple(variable):
    try:
        len(variable)
        variable.count(0)
    except (TypeError, AttributeError):
        print(f"{variable} is not a tuple")
        return False
    else:
        print(f"{variable} is a tuple")
        return True
 
 
print(is_tuple((1, 2, 3)))
print(is_tuple("hello"))
print(is_tuple(123))


Output

(1, 2, 3) is a tuple
True
hello is not a tuple
False
123 is not a tuple
False

Time Complexity: O(1)
Auxiliary Space: O(1)



Last Updated : 25 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads