Determining variable type
![]()
You can check what type of object is assigned to a variable using Python’s built-in type() function. Common data types include:
- int (for integer)
- float
- str (for string)
- list
- tuple
- dict (for dictionary)
- set
- bool (for Boolean True/False)
_is used as because we can’t use space in the name, use _instead
Python is a case—sensitive language.
This means Variable and variable are not the same. Always name identifiers that make sense.
While, c = 10 is valid.
- List[] :- Collection of elements can be changed (mutable).
- Tuple():- Collection of elements can’t be changed (immutable).
- Set<> :- Collection of unique elements. Sets do not allow repetition
Python has the following data types built-in by default, in these categories:
Numeric Types: int , float , complex
Sequence Types: list , tuple , range
Mapping Type: dict
Set Types: set , frozenset
Boolean Type: bool
Binary Types: bytes , bytearray , memoryview
Here is a simple code which can make you understand better
The following code example would print the data type of x, what data type would that be?
One should not use space in between my and income surely it will show the syntax
The output “int”(integer type)
For the above-given codes, we can assign a value called a & b respectively
Assigning Variables
Variable assignment follows name = object , where a single equals sign = is an assignment operator
Reassigning Variables
Python lets you reassign variables with a reference to the same object.
There’s actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using += , -= , *= , and /= .
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
Определяем типы данных в Python. Изменяемые и неизменяемые типы
В этой статье мы поговорим, как определить тип переменной в Python. Заодно, расскажем, почему одни переменные считают изменяемыми, а другие нет. И какие тут существуют тонкости, связанные с терминологией.
В некоторых случаях нужно определить тип данных переменной в Python. Проверить, к какому типу принадлежит та или иная переменная, можно посредством функции type:
Также мы можем определить тип данных переменной в Python посредством функции isinstance() :
Здесь стоит обратить внимание, что isinstance() в отличие от type даёт возможность проверять тип данных на принадлежность хотя бы одному типу из кортежа, который передан в качестве 2-го аргумента:
Также следует упомянуть и другое, не менее значимое достоинство isinstance() — поддержка наследования. Для isinstance() экземпляр производного класса является экземпляром его базового класса:
Проверка типов
Есть и ещё кое-что: во время преобразования типов данных переменных в Python нередко возникают следующие ошибки:
Впрочем, ошибка является вполне логичной, ведь мы пробуем преобразовать в десятичный формат строку „a“.
Понятно, что на практике вы с такой ошибкой не столкнётесь. Однако бывает, что надо, к примеру, пробежаться по списку строк, преобразовав в числа те, которые уже содержат числа. Чтобы ошибки избежать, нужно сначала определить, с каким типом переменных мы имеем дело.
В Python соответствующие средства, конечно, имеются. К примеру, используя метод isdigit() , мы определим, состоит ли наша строка из одних только цифр:
Есть и ещё один метод — isalpha() . Он проверит, состоит ли наша строка из одних лишь букв:
А вот isalnum() определит, состоит ли наша строка из цифр или букв:
Но давайте снова вернёмся к упомянутой в начале статьи функции type. Порой, в зависимости от результата, функция или библиотека может выводить различные типы объектов. К примеру, если объект только один, то возвращается строка, а если их несколько, то нам возвращается кортеж. Мы же хотим построить ход программы по иному, с учётом того, что было возвращено: строка либо кортеж. И здесь как раз и пригодится type:
То же самое и с кортежем, и с иными типами данных:
Неизменяемые и изменяемые данные в Python
Считается, что все типы данных в языке программирования Python можно отнести к любой из двух категорий: — изменяемые (mutable); — неизменяемые (unmutable).
И многие из предопределённых типов являются типами неизменяемых объектов: — символьные строки (class ‘str’); — числовые данные (int, float, complex); — кортежи (tuple).
Что касается других типов, то они определены как изменяемые: — множества (set), — списки (list), — словари (dict).
Кроме того, вновь определяемые пользователем классы (типы) тоже можно определить как изменяемые или неизменяемые. И вообще, изменяемость объектов какого-нибудь типа считается принципиально значимой характеристикой, которая определяет, способен ли объект такого типа выступать в виде ключа для словарей (dict) либо нет.
И тут есть один интересный нюанс, связанный с самой терминологией «изменяемый-неизменяемый» (именно она используется в русскоязычном переводе). На самом деле, такой вариант названия не совсем удачный, он вносит неоднозначность. Здесь скорее бы подошёл термин «мутирующий-немутирующий», т. к. он лучше отображает суть происходящего. А суть заключается в том, способен ли объект данного типа менять свою структурность?
К примеру строка s = ‘abcdef’ относится к неизменяемому типу, ведь в Python нельзя (это вам не C/C++) поменять какой-нибудь одиночный символ в строке, допустим, через s[ 2 ] = ‘z’, и это не говоря о том, чтобы вставить символ внутрь строки. Однако мы можем сделать s = s[ :2 ] + ‘z’ = s[ 3: ] и получить в итоге нужную строку ‘abzdef’, но это будет абсолютно другая строка, размещённая по абсолютно другому адресу в памяти, то есть s — переустановленная ссылка на новую строку. Однако поменять строку либо её длину (структурность) по текущей ссылке нельзя. В этом, как раз, и заключается неизменяемость объекта — неконстантность, ведь его значение поменять можно, однако это уже будет ссылка на другой объект с новым значением.
На этом всё, если хотите прокачать навыки Python-программирования «по-врослому», записывайтесь на курсы в OTUS:
How to determine a Python variable's type?
![]()
To check if a variable is of a given type, use isinstance :
Note that Python doesn’t have the same types as C/C++, which appears to be your question.
You may be looking for the type() built-in function.
See the examples below, but there’s no «unsigned» type in Python just like Java.
Large positive integer:
Literal sequence of characters:
Floating point integer:
It is so simple. You do it like this.
![]()
How to determine the variable type in Python?
So if you have a variable, for example:
You want to know its type?
There are right ways and wrong ways to do just about everything in Python. Here’s the right way:
Use type
You can use the __name__ attribute to get the name of the object. (This is one of the few special attributes that you need to use the __dunder__ name to get to — there’s not even a method for it in the inspect module.)
Don’t use __class__
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 absolutely necessary.)
Since type gives us the class of the object, we should avoid getting this directly. :
This is usually the first idea people have when accessing the type of an object in a method — they’re already looking for attributes, so type seems weird. For example:
Don’t. Instead, do type(self):
Implementation details of ints and floats
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?
In Python, these specifics are implementation details. So, in general, we don’t usually worry about this in Python. However, to sate your curiosity.
In Python 2, int is usually a signed integer equal to the implementation’s word width (limited by the system). It’s usually implemented as a long in C. When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).
For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:
In Python 3, the old int goes away, and we just use (Python’s) long as int, which has unlimited precision.
We can also get some information about Python’s floats, which are usually implemented as a double in C:
Conclusion
Don’t use __class__ , a semantically nonpublic API, to get the type of a variable. Use type instead.
And don’t worry too much about the implementation details of Python. I’ve 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.
![]()
I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.
Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.
![]()
Examples of simple type checking in Python:
![]()
One more way using __class__ :
![]()
It may be little irrelevant. but you can check types of an object with isinstance(object, type) as mentioned here.
The question is somewhat ambiguous — I’m not sure what you mean by «view». If you are trying to query the type of a native Python object, @atzz’s answer will steer you in the right direction.
However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t , int16_t ), use the struct module. You can determine the number of bits in a given C-type primitive thusly:
This is also reflected in the array module, which can make arrays of these lower-level types:
The maximum integer supported (Python 2’s int ) is given by sys.maxint.
There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:
For float data and precision data, use sys.float_info:
Do you mean in Python or using ctypes?
In the first case, you simply cannot — because Python does not have signed/unsigned, 16/32 bit integers.
In the second case, you can use type() :
For more reference on ctypes, an its type, see the official documentation.
Python doesn’t have such types as you describe. There are two types used to represent integral values: int , which corresponds to platform’s int type in C, and long , which is an arbitrary precision integer (i.e. it grows as needed and doesn’t have an upper limit). int s are silently converted to long if an expression produces result which cannot be stored in int .
Simple, for python 3.4 and above
Python 2.7 and above
It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint ) and long (unlimited precision), for historical reasons. In Python code, this shouldn’t make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that’s implementation dependent. (CPython’s are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.
For python2.x, use
For python3.x, use
![]()
You should use the type() function. Like so:
This function will view the type of any variable, whether it’s a list or a class. Check this website for more information: https://www.w3schools.com/python/ref_func_type.asp
![]()
Python is a dynamically typed language. A variable, initially created as a string, can be later reassigned to an integer or a float. And the interpreter won’t complain:
To check the type of a variable, you can use either type() or isinstance() built-in function. Let’s see them in action:
Let’s compare both methods performances in python3
type is 40% slower approximately (54.5/39.2 = 1.390).
We could use type(variable) == str instead. It would work, but it’s a bad idea:
- == should be used when you want to check the value of a variable. We would use it to see if the value of the variable is equal to "hello_world". But when we want to check if the variable is a string, is the operator is more appropriate. For a more detailed explanation of when to use one or the other, check this article.
- == is slower: python3 -m timeit -s "variable = ‘hello_world’" "type(variable) == str" 5000000 loops, best of 5: 64.4 nsec per loop
Difference between isinstance and type
Speed is not the only difference between these two functions. There is actually an important distinction between how they work:
- type only returns the type of an object (it’s class). We can use it to check if the variable is of type str.
- isinstance checks if a given object (first parameter) is:
- an instance of a class specified as a second parameter. For example, is variable an instance of the str class?
- or an instance of a subclass of a class specified as a second parameter. In other words — is variable an instance of a subclass of str?
What does it mean in practice? Let’s say we want to have a custom class that acts as a list but has some additional methods. So we might subclass the list type and add custom functions inside:
But now the type and isinstance return different results if we compare this new class to a list!
We get different results because isinstance checks if my_list is an instance of the list (it’s not) or a subclass of the list (it is because MyAwesomeList is a subclass of the list). If you forget about this difference, it can lead to some subtle bugs in your code.
Conclusions
isinstance is usually the preferred way to compare types. It’s not only faster but also considers inheritance, which is often the desired behavior. In Python, you usually want to check if a given object behaves like a string or a list, not necessarily if it’s exactly a string. So instead of checking for string and all its custom subclasses, you can just use isinstance.
On the other hand, when you want to explicitly check that a given variable is of a specific type (and not its subclass) — use type . And when you use it, use it like this: type(var) is some_type not like this: type(var) == some_type .
How to Check Data Type in Python | Type() Function & More

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.
Output:
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.
Output:
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.
Output:
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__.
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)
The syntax of assert is :
assert condition, message
It is used just like ‘raise’ to throw an exception but here, a condition is also specified.
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.
And you will obtain the given output
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.