Python Datatypes
Datatype of a variable defines the characteristics of the data stored in that variable and different functions that can be performed on it.
In Python, there are some built in datatypes. These can be categorised based on the type of data like numeric, ordered, unordered, character based, etc.
The following table describes the category and the datatypes that fall into that specific category.
Category | Datatypes |
---|---|
Boolean | bool |
Binary | bytes, bytearray, memoryview |
Numeric | int, float, complex |
Sequence | list, tuple, range |
Set | set, frozenset |
Mapping | dict |
Text | str |
In this tutorial, we will go through a few examples for each of the datatypes.
Boolean Datatype
A Boolean is used to store either True or False.
a = True
a = False
Binary Datatypes
Binary datatypes allow us to work with the values at binary level like accessing at a byte level.
There are three datatypes that belong to binary category.
- bytes
- bytesarray
- memoryview
#bytes
a = b"Hello World"
#bytearray
a = bytearray(5)
#memoryview
a = memoryview(bytes(5))
In the following example, we print the binary type values assigned to the variables.
Example.py
a = b"Hello World"
print(a)
a = bytearray(5)
print(a)
a = memoryview(bytes(5))
print(a)
Output
b'Hello World'
bytearray(b'\x00\x00\x00\x00\x00')
<memory at 0x1065cd700>
Numeric Datatypes
To work with numeric values Python provides three datatypes. They are
- int
- float
- complex
int
is used to store integer values.
a = 10
a = 25
float
is used to store floating point values.
a = 3.14
a = 10.00012
complex
is used to store complex (real, imaginary) numbers.
a = 3 + 4j
Sequence Datatypes
A sequence is an ordered collection of items. In here items are stored in order, and can be accessed by using its position/index in this sequence.
Python provides three types of sequences.
- list
- tuple
- range
List is a mutable sequence.
a = [1, 5, 6, 4]
Tuple is an immutable sequence.
a = (2, 3, 5)
Range is a sequence of numbers.
a = range(1, 8)
Set Datatypes
set
datatype is a collection of items where order of items is not considered. We cannot access the items using position/index.
a = {1, 5, 7, 6, 20, 9}
Mapping Datatype
There is only one kind of mapping datatype in Python. It’s a dictionary, dict
.
A dictionary is a set of key: value pairs. Keys are unique.
a = {'a': 25, 'b': 50}
Text Datatype
str
is the text datatype in Python.
str datatype is used to store strings.
a = 'Hello World'
Conclusion
In this Python Tutorial, we learned different datatypes in Python, with examples.