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 есть две функции type() и isinstance() с помощью которых можно проверить к какому типу данных относится переменная.
Разница между type() и isinstance()
type() возвращает тип объекта
isinstance() возвращает boolean значение — принадлежит объект данному типу или нет
Встроенная функция type() это самый простой способ выяснить тип объекта. В Python всё является объектом, объекты делятся на изменяемые и неизменяемые .
Вы можете воспользоваться type() следующим образом.
Пример использования type()
В Python четырнадцать типов данных.
Для начала рассмотрим три численных типа (Numeric Types):
- int (signed integers)
- float (вещественные числа с плавающей точкой)
- complex (комплексные числа)
Создайте три переменные разного численного типа и проверьте работу функции:
var_int = 1380 var_float = 3.14 var_complex = 2.0-3.0j print (type(var_int)) print (type(var_float)) print (type(var_complex))
Рассмотрим ещё несколько примеров
# Text Type: var_str = 'heihei.ru' # Boolean Type: var_bool = True # Sequence Types: var_list = [ 'heihei.ru' , 'topbicycle.ru' , 'urn.su' ] var_tuple = ( 'andreyolegovich.ru' , 'aredel.com' ) var_range = range(0,9) print (type(var_str)) print (type(var_bool)) print (type(var_list)) print (type(var_tuple)) print (type(var_range))
Спецификацию функции type() вы можете прочитать на сайте docs.python.org
Команда type
Есть ещё полезная команда type которая решает другую задачу.
С помощью команды type можно, например, определить куда установлен Python.
Подробнее об этом можете прочитать здесь
python3 is hashed (/usr/bin/python3)
python3 is hashed (/usr/bin/python)
isinstance()
Кроме type() в Python есть функция isinstance(), с помощью которой можно проверить не относится ли переменная к какому-то определённому типу.
Иногда это очень удобно, а если нужно — всегда можно на основе isinstance() написать свою функцию.
Пример использования
Создадим пять переменных разного типа и проверим работу функции
var_int = 1380 var_str = 'heihei.ru' var_bool = True var_list = [ 'heihei.ru' , 'topbicycle.ru' , 'urn.su' ] var_tuple = ( 'andreyolegovich.ru' , 'aredel.com' ) if ( isinstance (var_int , int )): print ( f» < var_int >is int» ) else : print ( f» < var_int >is not int» ) if ( isinstance (var_str , str )): print ( f» < var_str >is str» ) else : print ( f» < var_str >is not str» ) if ( isinstance (var_bool , bool )): print ( f» < var_bool >is bool» ) else : print ( f» < var_bool >is not bool» ) if ( isinstance (var_list , list )): print ( f» < var_list >is list» ) else : print ( f» < var_list >is not list» ) if ( isinstance (var_tuple , tuple)): print ( f» < var_tuple >is tuple» ) else : print ( f» < var_tuple >is not tuple» )
1380 is int heihei.ru is str True is bool ['heihei.ru', 'topbicycle.ru', 'urn.su'] is list ('andreyolegovich.ru', 'aredel.com') is tuple
Из isinstance() можно сделать аналог type()
Напишем свою фукнцию по определению типа typeof() на базе isinstance
def typeof(your_var): if ( isinstance (your_var, int)): return 'int' elif ( isinstance (your_var, bool)): return 'bool' elif ( isinstance (your_var, str)): return 'str' elif ( isinstance (your_var, list)): return 'list' elif ( isinstance (your_var, tuple)): return 'tuple' else : print(«type is unknown»)
Протестируем нашу функцию
var_list is list
Принадлежность к одному из нескольких типов
Если нужно проверить принадлежит ли объект не к какому-то одному, а к группе типов, эти типы можно перечислить в скобках.
Часто бывает нужно проверить является ли объект числом, то есть подойдёт как int, так и float
print ( isinstance ( 2.0 , ( int , float )))
Проверим несколько значений из списка
l3 = [ 1.5 , — 2 , "www.heihei.ru" ] for item in l3: print ( isinstance (item, ( int , float )))
True
True
False
Проверка списка или другого iterable
Часто бывает нужно проверить не одну переменную а целый список, множество, кортеж или какой-то другой объект.
Эту задачу можно решить с помощью isinstance() и функций:
- all()
- map()
- и лямбда функций
Проверить все ли элементы списка l1 int
l1 = [ 1 , 2 , 3 ] if all ( map ( lambda p: isinstance (p, int ), l1)): print ( "all int in l1" )
Проверить несколько списков на int и float
l1 = [ 3 , — 4.0 , 5.5 , — 6.2 ] l2 = [ 1 , — 2 , "test" ] def verif_list (l): return ( all ( map ( lambda p: isinstance (p, ( int , float )), l))) if __name__ == "__main__" : print (verif_list(l1)) print (verif_list(l2))
Помимо isinstance() в Python есть функция issubclass() с помощью которой проверяется является один класс производным от другого.
В других языках
- Си: такой функции нет.
- C++: похожую задачу решает функция typeid()
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.
![]()
One more way using __class__ :
![]()
Examples of simple type checking in Python:
![]()
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 .
Как узнать тип переменной python
Переменные предназначены для хранения данных. Название переменной в Python должно начинаться с алфавитного символа или со знака подчеркивания и может содержать алфавитно-цифровые символы и знак подчеркивания. И кроме того, название переменной не должно совпадать с названием ключевых слов языка Python. Ключевых слов не так много, их легко запомнить:
Например, создадим переменную:
Здесь определена переменная name , которая хранит строку «Tom».
В пайтоне применяется два типа наименования переменных: camel case и underscore notation .
Camel case подразумевает, что каждое новое подслово в наименовании переменной начинается с большой буквы. Например:
Underscore notation подразумевает, что подслова в наименовании переменной разделяются знаком подчеркивания. Например:
И также надо учитывать регистрозависимость, поэтому переменные name и Name будут представлять разные объекты.
Определив переменную, мы можем использовать в программе. Например, попытаться вывести ее содержимое на консоль с помощью встроенной функции print :
Например, определение и применение переменной в среде PyCharm:

Отличительной особенностью переменной является то, что мы можем менять ее значение в течение работы программы:
Типы данных
Переменная хранит данные одного из типов данных. В Python существует множество различных типов данных. В данном случае рассмотрим только самые базовые типы: bool , int , float , complex и str .
Логические значения
Тип bool представляет два логических значения: True (верно, истина) или False (неверно, ложь). Значение True служит для того, чтобы показать, что что-то истинно. Тогда как значение False , наоборот, показывает, что что-то ложно. Пример переменных данного типа:
Целые числа
Тип int представляет целое число, например, 1, 4, 8, 50. Пример
По умолчанию стандартные числа расцениваются как числа в десятичной системе. Но Python также поддерживает числа в двоичной, восьмеричной и шестнадцатеричной системах.
Для указания, что число представляет двоичную систему, перед числом ставится префикс 0b :
Для указания, что число представляет восьмеричную систему, перед числом ставится префикс 0o :
Для указания, что число представляет шестнадцатеричную систему, перед числом ставится префикс 0x :
Стоит отметить, что в какой-бы системе мы не передали число в функцию print для вывода на консоль, оно по умолчанию будет выводиться в десятичной системе.
Дробные числа
Тип float представляет число с плавающей точкой, например, 1.2 или 34.76. В качесте разделителя целой и дробной частей используется точка.
Число с плавающей точкой можно определять в экспоненциальной записи:
Число float может иметь только 18 значимых символов. Так, в данном случае используются только два символа — 3.9. И если число слишком велико или слишком мало, то мы можем записывать число в подобной нотации, используя экспоненту. Число после экспоненты указывает степень числа 10, на которое надо умножить основное число — 3.9.
Комплексные числа
Тип complex представляет комплексные числа в формате вещественная_часть+мнимая_часть j — после мнимой части указывается суффикс j
Строки
Тип str представляет строки. Строка представляет последовательность символов, заключенную в одинарные или двойные кавычки, например «hello» и ‘hello’. В Python 3.x строки представляют набор символов в кодировке Unicode
При этом если строка имеет много символов, ее можем разбить ее на части и разместить их на разных строках кода. В этом случае вся строка заключается в круглые скобки, а ее отдельные части — в кавычки:
Если же мы хотим определить многострочный текст, то такой текст заключается в тройные двойные или одинарные кавычки:
При использовани тройных одинарных кавычек не стоит путать их с комментариями: если текст в тройных одинарных кавычках присваивается переменной, то это строка, а не комментарий.
Управляющие последовательности в строке
Строка может содержать ряд специальных символов — управляющих последовательностей. Некоторые из них:
\ : позволяет добавить внутрь строки слеш
\’ : позволяет добавить внутрь строки одинарную кавычку
\» : позволяет добавить внутрь строки двойную кавычку
\n : осуществляет переход на новую строку
\t : добавляет табуляцию (4 отступа)
Применим несколько последовательностей:
Консольный вывод программы:
Хотя подобные последовательности могут нам помочь в некоторых делах, например, поместить в строку кавычку, сделать табуляцию, перенос на другую строку. Но они также могут и мешать. Например:
Здесь переменная path содержит некоторый путь к файлу. Однако внутри строки встречаются символы «\n», которые будут интерпретированы как управляющая последовательность. Так, мы получим следующий консольный вывод:
Чтобы избежать подобной ситуации, перед строкой ставится символ r
Вставка значений в строку
Python позволяет встравивать в строку значения других переменных. Для этого внутри строки переменные размещаются в фигурных скобках <>, а перед всей строкой ставится символ f :
В данном случае на место
будет вставляться значение переменной userName. Аналогично на вместо будет вставляться значение переменной userAge. Динамическая типизация
Python является языком с динамической типизацией. А это значит, что переменная не привязана жестко с определенному типу.
Тип переменной определяется исходя из значения, которое ей присвоено. Так, при присвоении строки в двойных или одинарных кавычках переменная имеет тип str . При присвоении целого числа Python автоматически определяет тип переменной как int . Чтобы определить переменную как объект float, ей присваивается дробное число, в котором разделителем целой и дробной части является точка.
При этом в процессе работы программы мы можем изменить тип переменной, присвоив ей значение другого типа:
С помощью встроенной функции type() динамически можно узнать текущий тип переменной: