Python find data type

How to Check Data Type in Python

Method 1: Using the type() function

To check the data type of a variable in Python, you can use the built-in “type()” method. The type() method “returns the class type of the argument(object) passed as a parameter.” For example, type(“Chat”) will return “str” because it is a string literal.

Syntax

Parameters

object: It is required; it can be a string, integer, list, tuple, set, dictionary, float, etc.

Example: How to Use type() function

str = 'AppDividend' print(type(str)) int = 123 print(type(int)) float = 21.19 print(type(float)) negative = -19 print(type(negative)) dictionary = print(type(dictionary)) list = [1, 2, 3] print(type(list)) tuple = (19, 21, 46) print(type(tuple))

How To Check Type Of Variable In Python

Method 2: Using an isinstance() function

To check any object in Python, you can use the isinstance()” function. The isinstance() function returns TRUE only when a stated object is of the desired type.

Example

data = isinstance("Hello", str) print(data)

Don’t use __class__ to check the data type in Python.

In Python, names that start with underscores are semantically not a part of the public API, and it’s a best practice for users to avoid using them. (Except when it’s compulsory.)

Since type gives us an object class, we should avoid getting __class__ directly.

class Foo(object): def foo(self): print(self.__class__) f = Foo() f.foo()

Let’s use type() function syntax, which is much better than this.

class Foo(object): def foo(self): print(type(self)) f = Foo() f.foo()

Don’t use __class__, a semantically nonpublic API, to get the variable type. Use type instead.

And don’t worry too much about the implementation details in Python.

I have not had to deal with issues around this myself. You probably won’t either, and if you really do, you should know enough not to be looking to this answer for what to do.

Difference Between type() Function and isinstance() Function

The isinstance() function returns true or false. On the other hand, the type() function returns the type of an object.

isinstance() function type() function
It returns a Boolean value It returns a String value
It takes two arguments It takes one argument
It checks for multiple classes It checks for only one object

Python isinstance() function is used to check if a specific value holds a particular data type, whereas type() provides us with the exact data type of that variable.

Источник

How to Check Data Type in Python | Type() Function & More

check data type python

Python has many built-in functions. In this tutorial, we will be discussing how to check the data type of the variables in python by using type(). As while programming in Python, we came to a situation where we wanted to check the data-type of the variable we use type() function. This article will help you understand the concept of type() function.

What is type() function?

Python type() is a built-in function that helps you find the class type of the variable given as input. You have to just place the variable name inside the type() function, and python returns the datatype.

Mostly, We use it for debugging purposes. we can also pass three arguments to type(), i.e., type(name, bases, dict). In such a case, it will return you a new type of object.

Syntax

Parameter

The object argument is the required parameter to be passed inside the type() function. The argument can be string, integer, list, tuple, set, dictionary, float, etc.

Syntax

Parameter

  • name: It is the name of the class.
  • bases: It is the optional parameter, and it is the name of the base class.
  • dict: It is an optional parameter, and it is the namespace that has a definition of the class.

Return value

  • If we pass only the object as the parameter, it will only return the object’s type.
  • If we pass the name, bases, and dict as the parameter, it will return the new type.

Examples to Check Data Type in Python

Let us discuss certain ways through which we can print the datatype of the variable.

1. Using type(object) Method to Check Data Type in Python

In this example, we will be taking the input in all the forms to write the variable like string, integer, negative value, float value, complex number, list, tuple, set, and dictionary. After that, we will print the data type of all the variables and see the output.

#taking input str = 'Python pool' print('Datatype : ',type(str)) num = 100 print('Datatype : ',type(num)) neg = -20 print('Datatype : ',type(neg)) float = 3.14 print('Datatype : ',type(float)) complex = 2 + 3j print('Datatype : ',type(complex)) lst = [1,2,3,4,5] print('Datatype : ',type(lst)) Tuple = (1,2,3,4,5) print('Datatype : ',type(Tuple)) Dict = print('Datatype : ',type(Dict)) set = print('Datatype : ',type(set))
Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype :

Explanation:

First, we declare the variables and then check the type using the type() function.

2. Using type(name, bases, dict) method to Check Data Type in Python

In this example, we will be taking all the parameters like name, bases, and dict. after that, we will print the output. Let see more clearly with the help of the program.

class Python: x = 'python pool'' y = 100 t1 = type('NewClass', (Python,), dict(x='Python pool', y=100)) print(type(t1)) print(vars(t1))

Explanation:

  • Firstly, we have taken a class, Python.
  • Then, we have taken a string and integer value inside the class python.
  • Then, we have taken a variable as t1 in which we have applied the type() with the parameter as name, bases, and dict
  • After that, we have printed the type of t1 and vars of t1.
  • At last, you can see the output.

Difference between type() and isinstance()

Type() Function

Python type() is a built-in function that helps you find the class type of the variable given as input.

Isinstance() Function

Python isinstance() function is used to check if the object (first argument) is an instance or subclass of classinfo class (second argument).

Example of type() and isinstance() function

In this example, we will be discussing about both the functions and explained in detail.

age = 100 print("Datatype : ",type(age)) age = isinstance(100,int) print("age is an integer:", age)
Datatype : age is an integer: True

Explanation:

  • Firstly, we have taken age as a variable with a value equal to 100.
  • Then, we have printed the datatype of the age value.
  • After that, we have applied isinstance() function with two parameters as the value of age and type of age.
  • At last, we have printed the output.
  • By seeing the output, we can see the difference between the type and isinstance function.

Checking Array Data Type (using if hasattr(N, “_len_”))

You can check the array data type using hasattr() function in python by specifying the function. For this you need to know the functions of the array. Here, __len__ provides the length of the data which you have passed. So if hasattr can determine a function that belongs to the array, we can call it array data type. Here, the function which we’ll use is __len__.

arr=[1,2,3] if hasattr(arr, '__len__'): print('array found') else: print('not found') #array found (Output)

Here, the __len__ function determined the length of the arr that was passed as an argument. This function belongs to array data type so we used ‘if’ to see if this attribute is present in array.

Checking for datatype of variable, else raise error (Using assert)

It is used just like ‘raise’ to throw an exception but here, a condition is also specified.

x = 'abc' print(type(x)) assert type(x) != int, 'x is an integer' print('x is not an integer')

Check if data type is boolean python

We can assess whether the given data belongs to boolean or not. In this case, you will put either True or False as the input to get a boolean type.

The type function is an easy-to-use tool to find the data type in Python.

Check data type Python Dataframe

To find the data type for a dataframe in python, you may use the dtype function.

import pandas as pd df = pd.DataFrame() print("DataFrame:") print(df) result = df.dtypes print("Output:") print(result) #Make sure that all the columns have the same size

And you will obtain the given output

DataFrame: A C 0 10 1.30 1 11 0.23 Output: A int64 C float64 dtype: object

FAQs

It is a function that helps to find out the data type of the attributes of a dataframe object in python.

We can check it using the type function.
var = 4 if type(var)==int: print(“Numeric”) else: print(“Not numeric”)

Conclusion

In this tutorial, we have learned how to check the variable’s data type by using type() with two different parameters. We have also explained all the variables using type() with examples explained in detail.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Источник

Читайте также:  Создать venv python 3 linux
Оцените статью