Data types · 2 / 29 Theory

Fundamentals of data types

A data type defines what kind of value something is and which operations can be done with it. Python is dynamically typed (the type is attached to the value, not to the variable) and strongly typed (it does not silently mix incompatible types: "2" + 3 raises an error).

Built-in data types

CategoryTypeExample
Numbersint42
Numbersfloat3.14
Numberscomplex2 + 3j
LogicboolTrue, False
Textstr"Hello"
Sequenceslist[1, 2, 3]
Sequencestuple(1, 2, 3)
Mappingsdict{"name": "Ana", "age": 25}
Setsset{1, 2, 3}
NothingNoneTypeNone

Checking the type of a value

print(type(42))          # <class 'int'>
print(type("Hello"))     # <class 'str'>
print(isinstance(3.14, float))   # True

Mutable and immutable types

  • Immutable values cannot be modified after they are created: int, float, bool, str, tuple. Any change creates a new value.
  • Mutable values can be changed in place: list, dict, set.
numbers = [1, 2, 3]
numbers.append(4)        # the same list now has 4 elements

text = "hello"
# text[0] = "H"          # error: strings are immutable
text = "H" + text[1:]    # creates a new string

Everything is an object

In Python even numbers and text are objects, with their own methods:

print("python".upper())    # PYTHON
print((255).bit_length())  # 8

In the next articles you will see the basic data types in detail and how to convert one type into another.