Beginner18 min

Built-in functions reference

The built-in functions worth knowing by heart, grouped by what they do, with runnable examples of each.

Why this matters in AI / ML / GenAI

Python ships around 70 built-ins that need no import. Knowing them stops you writing loops for things that are already one call, and shorter code has fewer places for bugs to hide.

1. Read

Understand the idea in plain English first.

2. Run

Load any example into the compiler and press Run.

3. Change

Edit one value, rerun, and learn from the output.

Types and conversion

int(), float(), str(), bool(), list(), tuple(), set(), dict(), frozenset(), bytes(), complex().

type(x) returns the class; isinstance(x, cls) checks membership and respects inheritance, which is why it is the one to use in real checks. isinstance accepts a tuple: isinstance(x, (int, float)).

repr() gives the unambiguous developer representation, str() the readable one. When debugging, print repr() — it shows quotes and escapes, so you can see that a value is "5 " with a trailing space rather than 5.

Sequences, aggregation, and iteration

len, sum, min, max, sorted, reversed, enumerate, zip, range, any, all, map, filter.

min and max accept a key function and a default for empty input. sorted accepts key and reverse. sum accepts a start value, which is how you sum from a non-zero base.

any and all short-circuit, so any(is_valid(x) for x in huge) stops at the first match rather than checking everything.

round(x, n) uses banker's rounding — round(2.5) is 2, not 3. That surprises people; use decimal when exact rounding matters.

Objects, introspection, and I/O

print, input, open, format, id, hash, dir, vars, getattr, setattr, hasattr, callable, help.

getattr(obj, "name", default) reads an attribute by string name with a fallback and is how plugin registries and config loaders work without a giant if-chain.

dir(obj) lists available attributes — the fastest way to explore an unfamiliar library object in a REPL.

abs, pow, divmod, bin, hex, oct, ord, chr cover numbers and characters. ord/chr convert between a character and its Unicode code point, which comes up in tokenizer work.

Avoid eval and exec on anything you did not write. Text from a user or an LLM run through eval is arbitrary code execution.

Hands-on practice

Compiler on the left. Examples on the right.

On desktop, keep the compiler beside the examples. On mobile, the same blocks stack cleanly. Pick an example, try it in the compiler, then change one small thing.

Build a summary using only built-ins

Live Python compiler

Try it — in-browser Python

Swap the key function to sort by name length instead of score.

Code editor

Output

Python runs in your browser. First run downloads the runtime.

Press Run (or Ctrl+Enter) to execute.

Runs CPython in your browser. NumPy, pandas, scikit-learn and Matplotlib load on demand. Charts appear below the output. No input(), no GPU, no network installs.

Clear code examples

Every example is copy-ready. Use Try in compiler when you want to experiment without scrolling around.

Example

Conversion and type checking

isinstance over type() — it respects inheritance.

values = ["42", 3.99, True, None, [1, 2]]

for v in values:
    print(f"{repr(v):<10} type={type(v).__name__:<6} bool={bool(v)}")

print("\nint('42')      ->", int("42"))
print("int(3.99)      ->", int(3.99), "(truncates, does not round)")
print("float('1e3')   ->", float("1e3"))
print("list('abc')    ->", list("abc"))
print("set([1,1,2])   ->", set([1, 1, 2]))
print("dict(a=1, b=2) ->", dict(a=1, b=2))

print("\nisinstance(True, int) ->", isinstance(True, int), "(bool subclasses int)")
print("type(True) is int     ->", type(True) is int)
print("isinstance(3.0, (int, float)) ->", isinstance(3.0, (int, float)))

Example

Aggregation with key functions

key= turns min, max, and sorted into general-purpose tools.

runs = [
    {"model": "mini", "acc": 0.91, "cost": 0.4},
    {"model": "large", "acc": 0.95, "cost": 3.2},
    {"model": "haiku", "acc": 0.89, "cost": 0.2},
]

print("best accuracy :", max(runs, key=lambda r: r["acc"])["model"])
print("cheapest      :", min(runs, key=lambda r: r["cost"])["model"])
print("total cost    :", round(sum(r["cost"] for r in runs), 2))
print("by acc desc   :", [r["model"] for r in sorted(runs, key=lambda r: -r["acc"])])

print("\nmin of empty with default:", min([], default="none"))
print("sum starting at 100      :", sum([1, 2, 3], 100))
print("round(2.5) ->", round(2.5), "| round(3.5) ->", round(3.5), "(banker's rounding)")

Example

any, all, enumerate, zip

any and all short-circuit, so they are cheap on large inputs.

scores = [0.91, 0.88, 0.94, 0.72]
names = ["mini", "large", "haiku", "local"]

print("all above 0.7 :", all(s > 0.7 for s in scores))
print("any above 0.93:", any(s > 0.93 for s in scores))
print("all of empty  :", all([]), "(vacuously true — a classic bug source)")
print("any of empty  :", any([]))

print("\nenumerate with a start value:")
for rank, (name, score) in enumerate(zip(names, scores), start=1):
    print(f"  {rank}. {name:<7} {score:.2f}")

print("\nzip stops at the shortest input:", list(zip([1, 2, 3], "ab")))
print("unzip with zip(*pairs):", list(zip(*[(1, "a"), (2, "b")])))

Example

Introspection: getattr, dir, hasattr

String-keyed attribute access replaces long if-chains.

class Config:
    model = "gpt-4.1-mini"
    temperature = 0.2
    max_tokens = 512

cfg = Config()

for field in ["model", "temperature", "top_p"]:
    print(f"{field:<12} present={hasattr(cfg, field)!s:<6} value={getattr(cfg, field, 'DEFAULT')}")

setattr(cfg, "top_p", 0.9)
print("\nafter setattr, top_p =", cfg.top_p)

public = [name for name in dir(cfg) if not name.startswith("_")]
print("public attributes:", public)
print("\ncallable(print) ->", callable(print), "| callable(cfg) ->", callable(cfg))

Example

Numbers and characters

ord and chr show up in tokenizer and encoding work.

print("abs(-7)      ->", abs(-7))
print("pow(2, 10)   ->", pow(2, 10))
print("pow(2,10,1000) ->", pow(2, 10, 1000), "(modular exponentiation)")
print("divmod(17, 5) ->", divmod(17, 5), "(quotient, remainder)")

print("\nbin(10) ->", bin(10), "| hex(255) ->", hex(255), "| oct(8) ->", oct(8))
print("int('ff', 16) ->", int("ff", 16))

print("\nord('A') ->", ord("A"), "| chr(97) ->", chr(97))
print("token ids for 'hi':", [ord(c) for c in "hi"])
print("back to text     :", "".join(chr(c) for c in [104, 105]))

Takeaways

  • Use isinstance, not type(), and pass a tuple to check several types at once.
  • key= makes min, max, and sorted work on any object; any/all short-circuit.
  • getattr with a default replaces if-chains; never eval untrusted or LLM-generated text.