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.

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

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
Try Online
ADVERTISEMENT

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))
Try Online

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)
Try Online

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
Try Online

float is used to store floating point values.

a = 3.14
a = 10.00012
Try Online

complex is used to store complex (real, imaginary) numbers.

a = 3 + 4j
Try Online

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]
Try Online

Tuple is an immutable sequence.

a = (2, 3, 5)
Try Online

Range is a sequence of numbers.

a = range(1, 8)
Try Online

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}
Try Online

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}
Try Online

Text Datatype

str is the text datatype in Python.

str datatype is used to store strings.

a = 'Hello World'
Try Online

Conclusion

In this Python Tutorial, we learned different datatypes in Python, with examples.