Beginner·18 min·0/47 done

Built-in functions reference

Built-in functions worth knowing, grouped by job, with tiny runnable demos.

Why it matters: Many everyday tasks need no import. Short built-in calls leave fewer places for bugs.

Basics

Types and conversion

Common converters: int(), float(), str(), bool(), list(), tuple(), set(), dict().

isinstance(x, cls) respects inheritance. Prefer it over type(x) is ....

repr(x) shows quotes and escapes - useful when debugging messy text.

Tiny example

Convert a string score and check its type.

raw = "0.91"
score = float(raw)
print(score, type(score).__name__)
print(isinstance(score, (int, float)))

Basics

Aggregate and iterate

Handy: len, sum, min, max, sorted, enumerate, zip, range, any, all.

min / max / sorted take key=. any / all stop early.

Common mistake: round(2.5) uses banker's rounding and can surprise you.

Tiny example

any, all, and enumerate on a short list.

scores = [0.9, 0.4, 0.8]
print(any(s >= 0.7 for s in scores))
print(all(s >= 0.7 for s in scores))
for i, s in enumerate(scores):
    print(i, s)

Basics

getattr and friends

getattr(obj, name, default), setattr, hasattr, and dir help explore objects.

Also useful: abs, pow, divmod, ord, chr.

Never eval / exec text from a user or an LLM.

Tiny example

Read an attribute by name with a default.

class Cfg:
    model = "mini"
cfg = Cfg()
print(getattr(cfg, "model"))
print(getattr(cfg, "temperature", 0.2))

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: pick best run with max(key=)

key= turns max into a leaderboard tool.

In AI / ML: Eval tables often select best accuracy or lowest cost this way.

example.py

Python

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:", max(runs, key=lambda r: r["acc"])["model"])
print("cheap:", min(runs, key=lambda r: r["cost"])["model"])
print("total cost:", round(sum(r["cost"] for r in runs), 2))

AI / ML example 2

AI / ML: config getattr defaults

Missing fields fall back without crashing.

In AI / ML: LLM clients read model, temperature, and max_tokens this way.

example.py

Python

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

cfg = Config()
for field in ["model", "temperature", "top_p"]:
    print(field, getattr(cfg, field, "DEFAULT"))

Takeaways

  • 1Prefer isinstance over type() checks.
  • 2key= makes min, max, and sorted work on records.
  • 3getattr with a default replaces long if-chains.
Certificate