Python tutorials · Part 2 of 8

Python data types

Every value in Python has a type that decides what you can do with it. Here are the built-in types you'll use every day, how to check them and how to convert between them.

Every value in Python has a type. The type decides what operations make sense: you can divide two numbers, but not two words; you can make a string upper-case, but not an integer. Python works the type out for you from the value, which is called dynamic typing, but you still need to know which type you're holding.

Checking a type

type() tells you the type of any value, and isinstance() checks whether a value is of a given type:

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

The main built-in types

Category Type Example
Numbers int, float, complex 42, 3.14, 2+3j
Text str "hello"
Truth bool True, False
Nothing NoneType None
Sequences list, tuple, range [1, 2], (1, 2), range(5)
Sets set, frozenset {1, 2}
Mappings dict {"a": 1}

Numbers: int and float

int holds whole numbers of any size; float holds numbers with a decimal point.

print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2)     # true division always gives a float
print(7 // 2)    # floor division
print(7 % 2)     # remainder
print(2 ** 10)   # power
9 5 14
3.5
3
1
1024

Floats are stored in binary, so some decimals can't be represented exactly:

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
0.30000000000000004
0.3
True

That's not a Python bug; it happens in every language. Never compare floats with == when the values come from calculations; compare with a small tolerance (or use math.isclose). For money, the decimal module gives exact decimal arithmetic.

Strings: str

A string is a sequence of characters in single or double quotes. Strings are immutable: methods return new strings rather than changing the original.

name = "Ada Lovelace"
print(name.upper())
print(name[0], name[-1], name[:3])
print(len(name), "Love" in name)
print(f"{name} was born in {1815}")
ADA LOVELACE
A e Ada
12 True
Ada Lovelace was born in 1815

f-strings (f"...") are the easiest way to put values inside text.

Booleans and None

bool has two values, True and False, and is what comparisons return. None means "no value", for example a missing result:

age = 20
print(age >= 18, age == 21)
result = None
print(result is None)
True False
True

Every value also has a truthiness: 0, 0.0, "", empty collections and None count as false in an if; almost everything else counts as true.

for value in [0, 7, "", "hi", [], [0], None]:
    print(repr(value), bool(value))
0 False
7 True
'' False
'hi' True
[] False
[0] True
None False

Collections: list, tuple, set and dict

  • list: ordered and changeable. [3, 1, 2]
  • tuple: ordered and unchangeable. (3, 1, 2). Good for fixed records like coordinates.
  • set: unordered, no duplicates, fast membership checks. {3, 1, 2}
  • dict: key–value pairs. {"x": 3}
print(set([3, 1, 3, 2, 1]))
point = (4, 5)
x, y = point
print(x + y)
{1, 2, 3}
9

Mutable types (list, dict, set) can be changed after creation; immutable ones (int, float, str, tuple, bool) can't. Only immutable values can be dictionary keys or set members.

Converting between types

Use the type's name as a function to convert, which is also called casting:

print(int("42") + 1)
print(float("3.5") * 2)
print(str(99) + " bottles")
print(int(3.99))
print(list("abc"), tuple([1, 2]))
43
7.0
99 bottles
3
['a', 'b', 'c'] (1, 2)

int() truncates towards zero; it doesn't round. Converting text that isn't a number raises a ValueError: int("3.5") and int("ten") both fail. That's why input(), which always returns a string, needs converting before you do arithmetic with it.

None vs NaN

None is Python's own "no value". When you work with numbers in NumPy or pandas, you'll also meet NaN ("not a number"), a special float that marks missing or undefined numeric values. They behave differently: None is None is true, but NaN isn't even equal to itself.

import math

nan = float("nan")
print(nan == nan)
print(math.isnan(nan))
print(None == None)
False
True
True

That's why you check for missing numbers with math.isnan() (or pandas.isna(), which handles both None and NaN), never with ==.

Type hints

Python doesn't force you to declare types, but you can annotate them. Type hints make code easier to read and let editors and tools like mypy catch mistakes before you run anything:

def average(values: list[float]) -> float:
    return sum(values) / len(values)

print(average([2.0, 4.0, 9.0]))
5.0

The hints don't change how the code runs: Python won't stop you from passing a list of strings. They're documentation that tools can check. Most modern libraries, including the ones you'll use for machine learning, ship with type hints, which is why your editor can autocomplete their functions so well.

Common mistakes

  • Adding a number to a string: "Age: " + 30 raises TypeError. Use str(30) or an f-string.
  • Forgetting that input() returns a string: "5" + "5" is "55".
  • Comparing floats with ==: use a tolerance.
  • / vs //: / always returns a float; // floors.
  • Using == None instead of is None.

Practice

  1. What are the types of 10 / 5, 10 // 5 and "10" * 2?
  2. Convert "3.7" to the integer 3.
  3. Which of 0, "0", [] and " " are truthy?

Answers

print(type(10 / 5).__name__, type(10 // 5).__name__, "10" * 2)
print(int(float("3.7")))
print([v for v in [0, "0", [], " "] if v])
float int 1010
3
['0', ' ']

Where this shows up in machine learning

Data types are at the root of many ML bugs. A column of numbers read from a CSV as strings won't train; a pandas column with type object usually means mixed or text values that need cleaning. NumPy and pandas add their own types, such as int64, float32, bool and category, and choosing float32 over float64 halves memory. Missing values show up as None or NaN, and knowing the difference is the first step in handling them.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.