Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Check if variable is tuple

Improve Article
Save Article
  • Last Updated : 15 Mar, 2023
Improve Article
Save Article

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

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

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)

Method: Attribute Check for Tuple

  1. Check if the input obj has both the __getitem__ and __iter__ attributes using the hasattr() function. This indicates that obj is an iterable object.
  2. If obj is iterable, check if it has both the count and index attributes using the hasattr() function. These attributes are unique to tuples in Python.
  3. Use the all() function to check if obj has both the count and index attributes. This ensures that obj is most likely a tuple.
  4. If obj has both the __getitem__ and __iter__ attributes and the count and index attributes, then it is likely a tuple and the function returns True.
  5. If obj is not iterable or it does not have both the __getitem__ and __iter__ attributes, then the function returns False.

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)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!