w3resource

Python: Test if a variable is a list or tuple or a set

Python Basic: Exercise-145 with Solution

Write a Python program to test if a variable is a list, tuple, or set.

Sample Solution-1:

Python Code:

#x = ['a', 'b', 'c', 'd']
#x = {'a', 'b', 'c', 'd'}
# Define a variable x with different data types (list, set, or tuple).
x = ('tuple', False, 3.2, 1)

# Check the type of x using the 'type()' function and print a message accordingly.
if type(x) is list:
    print('x is a list')
elif type(x) is set:
    print('x is a set')
elif type(x) is tuple:
    print('x is a tuple')    
else:
    print('Neither a list nor a set nor a tuple.')

Sample Output:

x is a tuple

Sample Solution-2:

Python Code:

# Define a function to check the type of a variable 'nums'.
def check_type(nums):
    # Check if 'nums' is a tuple and return a message.
    if isinstance(x, tuple) == True:
        return 'The variable x is a tuple'
    # Check if 'nums' is a list and return a message.
    elif isinstance(x, list) == True:
        return 'The variable x is a list'
    # Check if 'nums' is a set and return a message.
    elif isinstance(x, set) == True:
        return 'The variable x is a set'
    # If 'nums' is none of the above types, return a generic message.
    else:
        return 'Neither a list or a set or a tuple.'

# Define a variable 'x' as a list and check its type using the 'check_type' function.
x = ['a', 'b', 'c', 'd']
print(check_type(x))

# Define a variable 'x' as a set and check its type using the 'check_type' function.
x = {'a', 'b', 'c', 'd'}
print(check_type(x))

# Define a variable 'x' as a tuple and check its type using the 'check_type' function.
x = ('tuple', False, 3.2, 1)
print(check_type(x))

# Define a variable 'x' as an integer and check its type using the 'check_type' function.
x = 100
print(check_type(x))

Sample Output:

The variablex is a list
The variablex is a set
The variablex is a tuple
Neither a list or a set or a tuple.

Flowchart:

Flowchart: Test if a variable is a list or tuple or a set.

Python Code Editor :

 

Previous: Write a Python program to check whether variable is of integer or string.
Next: Write a Python program to find the location of Python module sources.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.