Python Tutorial Python Advanced Python References Python Libraries

Python - Data Types



One of the most important parts of learning any programming language is to understand what are the available data types, and how data is stored, accessed and manipulated in that language. Python is an object-orientated language, everything in Python is an object, and every value in Python has a datatype. Hence, in Python, data types are classes and variables are an instance (object) of these classes.

There are various data types in Python which can be categorized as below:

CategoryData Types
Textstr
Numericint, float, complex
Sequencelist, tuple, range
Mappingdict
Setset, frozenset
Booleanbool
Binarybytes, bytearray, memoryview

type() function

The Python type() function is used to find out the datatype of a specified variable. See the example below:

MyInt = 10
print(type(MyInt))

MyFloat = 10.5
print(type(MyFloat))

The output of the above code will be:

<class 'int'>
<class 'float'>

Set datatype of a variable

Unlike Java & C++, Python does not require to declare a variable or its data type. The data type of a variable is set when a value is assigned to it. Below table describes how to set different data types in variable x.

Data TypesExample
strx = "Hello World!" or x = 'Hello World!'
intx = 10
floatx = 10.5
complexx = 5 + 5j
listx = [1, 2, 3]
tuplex = (1, 2, 3)
rangex = range(1, 5)
dictx = {'name': 'John', 'age': 25}
Setx = {1, 2, 3}
frozensetx = frozenset({1, 2, 3})
boolx = True
bytesx = b"Hello World!"
bytearrayx = bytearray(3)
memoryviewx = memoryview(bytes(3))

Set datatype of a variable using constructor

As discussed earlier, in Python, data types are classes and variables are an instance (object) of these classes. These data type classes have built-in function also known as constructor which can be used to construct an instance of the object. Below table describes how to set different data types in variable x using constructor.

Data TypesConstructorExample
strstr()x = str("Hello World!") or x = str('Hello World!')
intint()x = int(10)
floatfloat()x = float(10.5)
complexcomplex()x = complex(5 + 5j)
listlist()x = list((1, 2, 3))
tupletuple()x = tuple((1, 2, 3))
rangerange()x = range(1, 5)
dictdict()x = dict(name='John', age=25)
Setset()x = set((1, 2, 3))
frozensetfrozenset()x = frozenset((1, 2, 3)
boolbool()x = boot(1)
bytesbyte()x = bytes(3)
bytearraybytearray()x = bytearray(3)
memoryviewmemoryview()x = memoryview(bytes(3))