SkillByAIOpen interactive version →

Lesson 6 / 49

Data Types

Work with Python's core types: int, float, str, bool and None, plus lists, tuples, sets and dictionaries.

Scalars

int (unbounded), float, complex, str (immutable), bool, and None.

The four collections

list mutable/ordered · tuple immutable · set unique/unordered · dict key→value.

nums = [1, 2, 3]
nums.append(4)
point = (10, 20)
tags = {"a", "b"}
person = {"name": "Ada", "age": 36}
person["age"]        # 36

Numbers and booleans

int has no size limit, float is a 64-bit decimal approximation (so 0.1 + 0.2 is not exactly 0.3), and bool is a subclass of int where True == 1.

big = 2 ** 100          # int never overflows
price = 19.99           # float
active = True           # bool

0.1 + 0.2               # 0.30000000000000004
True + True             # 2
7 // 2, 7 % 2, 7 / 2    # (3, 1, 3.5)

Checking types: type() and isinstance()

type(x) tells you the exact type; isinstance(x, T) is the preferred check because it also accepts subclasses.

type(42)                    # <class 'int'>
type("hi")                  # <class 'str'>
isinstance(3.5, float)      # True
isinstance(True, int)       # True (bool is an int)
isinstance(3, (int, float)) # True: any of several types

Type conversion

Convert explicitly with int(), float(), str() and bool(). Bad input raises ValueError. Empty values (0, "", [], None) are falsy.

int("42")        # 42
float("3.14")    # 3.14
str(7)           # "7"
int(3.9)         # 3  (truncates, does not round)
bool("")         # False
bool("0")        # True (non-empty string)
int("abc")       # ValueError

Quick check: What does int(3.9) return?

  • 4
  • 3
  • 3.9
  • ValueError
Answer

3 — int() truncates toward zero; use round() to round.

Quick check: Which collection is immutable?

  • list
  • dict
  • tuple
  • set
Answer

tuple — A tuple can't be changed after creation.