How To Check If Variable Is Array In Python

In Python, it is a common practice to check the data type of a variable, especially when working with arrays.

Arrays are widely used to store collections of data, and knowing how to check if a variable is an array can make your code more robust and efficient. In this tutorial, we will discuss different ways to check if a variable is an array in Python.

Step 1: Using the isinstance() function

The simplest way to check if a variable is an array is by using the isinstance() function. This function checks if the given object (first argument) is an instance or subclass of a specified class or a tuple of classes (second argument).

In the case of arrays, you need to check if the variable is an instance of the built-in Python list, tuple, or numpy.ndarray classes.

Here’s an example of how to use the isinstance() function:

Step 2: For NumPy arrays

If you’re working with NumPy arrays, you need to import the numpy library and modify the isinstance() function call to include the numpy.ndarray class. Here’s an example:

Step 3: Using a custom function

You can also create a custom function named is_array() that checks if a variable is an array (list, tuple, or NumPy array). Here’s an example:

Full code

Here’s the full code combining all the methods above:

Output

variable1 is an array using isinstance()
variable2 is an array using isinstance()
variable1 is an array using custom function
variable2 is an array using custom function
variable3 is not an array

Conclusion

In this tutorial, we have discussed different ways to check if a variable is an array in Python. We used the built-in isinstance() function as well as created a custom function called is_array().

By implementing these methods in your code, you can ensure that your code is more robust and efficient when working with arrays.