How To Check If An Element Is A List In Python

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:

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:

Output:

Yes, element is a list!

Full Code:

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.