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:
Category | Data Types |
---|---|
Text | str |
Numeric | int, float, complex |
Sequence | list, tuple, range |
Mapping | dict |
Set | set, frozenset |
Boolean | bool |
Binary | bytes, bytearray, memoryview |
The Python type() function is used to findout the datatype of a specified variable. Please see the example below.
MyInt = 10 print(type(MyInt)) MyFloat = 10.5 print(type(MyFloat))
<class 'int'> <class 'float'>
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 Types | Example |
---|---|
str | x = "Hello World!" or x = 'Hello World!' |
int | x = 10 |
float | x = 10.5 |
complex | x = 5 + 5j |
list | x = [1, 2, 3] |
tuple | x = (1, 2, 3) |
range | x = range(1, 5) |
dict | x = {'name': 'John', 'age': 25} |
Set | x = {1, 2, 3} |
frozenset | x = frozenset({1, 2, 3}) |
bool | x = True |
bytes | x = b"Hello World!" |
bytearray | x = bytearray(3) |
memoryview | x = memoryview(bytes(3)) |
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 ann instance of the object. Below table describes how to set different data types in variable x using constructor.
Data Types | Constructor | Example |
---|---|---|
str | str() | x = str("Hello World!") or x = str('Hello World!') |
int | int() | x = int(10) |
float | float() | x = float(10.5) |
complex | complex() | x = complex(5 + 5j) |
list | list() | x = list((1, 2, 3)) |
tuple | tuple() | x = tuple((1, 2, 3)) |
range | range() | x = range(1, 5) |
dict | dict() | x = dict(name='John', age=25) |
Set | set() | x = set((1, 2, 3)) |
frozenset | frozenset() | x = frozenset((1, 2, 3) |
bool | bool() | x = boot(1) |
bytes | byte() | x = bytes(3) |
bytearray | bytearray() | x = bytearray(3) |
memoryview | memoryview() | x = memoryview(bytes(3)) |