In Python, a list is a mutable, ordered collection of elements that are enclosed in square brackets. Checking if an element is a list is essential when dealing with any kind of data manipulation task. This tutorial will guide you on how to check if an element is a list in Python.
Step 1: Using the type() Function
The first method to check if an element is a list involves using the built-in type() function. The type() function returns the type of the given object as an output. Let’s see an example:
1 2 3 4 5 |
element = [1, 2, 3] if type(element) == list: print("Yes, element is a list!") else: print("No, element is not a list!") |
Output:
Yes, element is a list!
Step 2: Using the isinstance() Function
Another approach to check if an element is a list is using the isinstance() function. This built-in function checks if the given object is an instance of the specified class or a tuple of classes. Here’s an example:
1 2 3 4 5 |
element = [1, 2, 3] if isinstance(element, list): print("Yes, element is a list!") else: print("No, element is not a list!") |
Output:
Yes, element is a list!
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Checking if an element is a list using type() function element1 = [1, 2, 3] if type(element1) == list: print("Yes, element1 is a list!") else: print("No, element1 is not a list!") # Checking if an element is a list using isinstance() function element2 = [4, 5, 6] if isinstance(element2, list): print("Yes, element2 is a list!") else: print("No, element2 is not a list!") |
Output:
Yes, element1 is a list! Yes, element2 is a list!
Conclusion
In this tutorial, you’ve learned how to check if an element is a list in Python using two different methods: by using the type() function and the isinstance() function.
Both approaches are effective, but using isinstance() is recommended since it also works with subclasses, making it more flexible and versatile.