Python Data Types

Every value in Python has a type, and the built-in types cover text, numbers, sequences, mappings, sets, and more.

Types describe values

In Python the type belongs to the value, not to the variable. When you assign a value, Python records what kind of thing it is, and you can inspect that at any time with the built-in type() function. Knowing a value's type tells you which operations are allowed on it, for example that you can add numbers but concatenate strings.

Checking types with type()

x = 42
y = 3.14
name = "Python"

print(type(x))      # <class 'int'>
print(type(y))      # <class 'float'>
print(type(name))   # <class 'str'>

The built-in data types

Python groups its standard types by the kind of data they represent. The table below lists the most common ones you will meet early on, with a short example of each.

CategoryTypeExample value
Textstr"hello"
Numericint100
Numericfloat3.14
Numericcomplex2 + 3j
Sequencelist[1, 2, 3]
Sequencetuple(1, 2, 3)
Sequencerangerange(5)
Mappingdict{"id": 1}
Setset{1, 2, 3}
BooleanboolTrue
NoneNoneTypeNone

A useful way to group these is by whether they can be changed after creation. Mutable types can be modified in place, while immutable types cannot, so an operation that looks like a change actually produces a new value.

  • Immutable types: int, float, complex, bool, str, tuple, and frozenset.
  • Mutable types: list, dict, and set.
  • Sequences (str, list, tuple, range) support indexing and slicing.
  • The bool type is a special kind of int, where True equals 1 and False equals 0.

Values of several types

flag = True                 # bool
prices = [9.99, 19.99]      # list of floats
person = {"name": "Lee"}   # dict
nothing = None              # NoneType

print(type(flag), type(prices), type(person), type(nothing))
Note: You rarely set a type by hand. Python infers it from the literal you write: quotes make a str, square brackets make a list, curly braces with colons make a dict, and so on.

Exercise: Python Data Types

Which function tells you the data type of a variable?