Home »
Python »
Python Programs
How to check if a variable is either a Python list, NumPy array, or pandas series?
Learn, how can we check if a variable is either a Python list, NumPy array, or pandas series?
Submitted by Pranit Sharma, on September 17, 2022
Prerequisite
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
A Python list is a collection of heterogeneous elements and it is mutable in nature. Tuples are also another built-in data type of python used to store heterogeneous elements. Elements inside the list are encapsulated in square brackets whereas elements inside tuples are encapsulated in normal parenthesis. Both list and tuples are considered as a series or collection and we can perform operations like insert, update, and delete with its elements.
Pandas series contains a single list that can store heterogeneous types of data, because of this, the series is also considered a 1-dimensional data structure. When we analyze a series, each value can be considered as a separate row of a single column.
And, NumPy is an array processing package which provides high-performance multidimensional array.
Problem statement
Given a variable, we have to check if a variable is either a Python list, NumPy array, or pandas series.
Check whether a given is variable is a Python list, a NumPy array or a Pandas Series
For this purpose, you can simply use the type() method by providing the variable name, The type() method is a built-in method that determines and returns the type of the given parameter. Based on the return value (class) you can determine whether the given variable is a list, NumPy array, or pandas series.
Let us understand with the help of an example,
Python program to check if a variable is either a Python list, NumPy array, or pandas series
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a list
l = [1, 2, 3, 4, 5]
# Creating a numpy array
arr = np.array(l)
# Creating a pandas Series
ser = pd.Series(l)
# Checking type of each item
print("type of L :", type(l))
print("type of arr :", type(arr))
print("type of Ser :", type(ser))
Output
type of L : <class 'list'>
type of arr : <class 'numpy.ndarray'>
type of Ser : <class 'pandas.core.series.Series'>
Python Pandas Programs »