Python Tutorial
Python Built-in Functions Reference
Python ships with about 70 built-in functions that are always available without importing anything. You have already used print, len and range; the rest cover type conversion, math, iteration, object inspection, input/output and dynamic code execution.
This reference groups every commonly used built-in by purpose — abs, all, any, ascii, bin, bool, bytearray, bytes, callable, chr, compile, complex, delattr, dict, dir, divmod, enumerate, eval, exec, filter, float, format, frozenset, getattr, globals, hasattr, hash, help, hex, id, input, int, isinstance, issubclass, iter, len, list, locals, map, max, memoryview, min, next, object, oct, open, ord, pow, print, range, repr, reversed, round, set, setattr, slice, sorted, str, sum, tuple, type, vars and zip — with runnable examples for each group.
Numbers and Math
abs() absolute value; round(x, n) rounding (banker's rounding); pow(b, e, mod) power with optional modulus; divmod(a, b) quotient and remainder; min(), max(), sum() with optional key/default/start; bin(), oct(), hex() base strings; complex() complex numbers.
Type Construction and Conversion
int(), float(), str(), bool(), list(), tuple(), set(), frozenset(), dict(), bytes() (immutable), bytearray() (mutable bytes), memoryview() (zero-copy view of binary data), chr()/ord() for characters, ascii() and repr() for printable representations, format(value, spec) for formatting, and object() for a plain base object.
Iteration Helpers
range(), enumerate(), zip() (with strict=True to catch uneven lengths), reversed(), sorted(), map(), filter(), iter() and next() (manual iteration, with a default), all() and any(), len(), and slice() objects for reusable slices.
Objects and Introspection
type() and isinstance()/issubclass() check types; id() gives an object's identity; hash() its hash; callable() tests if it can be called; dir() lists attributes; vars() returns __dict__; getattr(), setattr(), hasattr(), delattr() work with attributes by name; globals() and locals() return namespaces; help() shows documentation.
I/O and Dynamic Execution
print() and input() for console I/O; open() for files. eval() evaluates an expression string, exec() executes statements, and compile() turns source into a code object. Never pass untrusted input to eval or exec — it can run any code; use ast.literal_eval to parse literals safely.
Examples
Numbers and math built-ins
print(abs(-7.5), round(2.675, 2), round(1234.5, -2))
print(pow(2, 10), pow(2, 10, 1000), divmod(47, 5))
print(min(4, 9, 1), max([3, 8, 2]), min([], default="empty"))
print(sum([1, 2, 3]), sum([[1], [2]], start=[]))
print(max(["pear", "fig", "banana"], key=len))
print(bin(10), oct(64), hex(255), complex(2, -3))
7.5 2.67 1200.0
1024 24 (9, 2)
1 8 empty
6 [1, 2]
banana
0b1010 0o100 0xff (2-3j)
Type construction and conversion built-ins
print(int("42"), float("2.5"), str(99), bool([]))
print(list("hi"), tuple({1: "a"}), sorted(set([3, 1, 3])), frozenset([1, 2]))
print(dict(a=1), dict([("b", 2)]))
print(bytes("₹5", "utf-8"), bytearray(b"abc"))
ba = bytearray(b"hello"); ba[0] = ord("j"); print(ba)
mv = memoryview(b"abcdef"); print(mv[1:4].tobytes(), len(mv))
print(chr(65), ord("a"), ascii("café ₹"), repr("line\n"))
print(format(1234.5678, ",.2f"), format(0.25, ".0%"), format(10, "08b"))
print(type(object()).__name__)
42 2.5 99 False
['h', 'i'] (1,) [1, 3] frozenset({1, 2})
{'a': 1} {'b': 2}
b'\xe2\x82\xb95' bytearray(b'abc')
bytearray(b'jello')
b'bcd' 6
A 97 'caf\xe9 \u20b9' 'line\n'
1,234.57 25% 00001010
object
Iteration built-ins
letters = ["a", "b", "c"]
print(list(range(2, 11, 3)), list(enumerate(letters, 1)))
print(list(zip(letters, [1, 2, 3])), list(reversed(letters)))
print(sorted([3, 1, 2], reverse=True))
print(list(map(str.upper, letters)), list(filter(lambda c: c != "b", letters)))
it = iter([10, 20])
print(next(it), next(it), next(it, "done"))
print(all([1, 2, 3]), any([0, 0, 1]), len({"a": 1, "b": 2}))
last_two = slice(-2, None)
print([1, 2, 3, 4][last_two], "python"[last_two])
try:
list(zip([1, 2], [1], strict=True))
except ValueError as e:
print("ValueError:", e)
[2, 5, 8] [(1, 'a'), (2, 'b'), (3, 'c')]
[('a', 1), ('b', 2), ('c', 3)] ['c', 'b', 'a']
[3, 2, 1]
['A', 'B', 'C'] ['a', 'c']
10 20 done
True True 2
[3, 4] on
ValueError: zip() argument 2 is shorter than argument 1
Object and introspection built-ins
class Course:
platform = "Webnest"
def __init__(self, title):
self.title = title
c = Course("Python")
print(type(c).__name__, isinstance(c, Course), issubclass(bool, int))
print(callable(Course), callable(c), callable(len))
print(vars(c), hasattr(c, "title"), getattr(c, "price", 0))
setattr(c, "price", 2999)
print(c.price)
delattr(c, "price")
print(hasattr(c, "price"))
print([name for name in dir(c) if not name.startswith("_")])
a = [1]
b = a
print(id(a) == id(b), hash("abc") == hash("abc"), hash((1, 2)) == hash((1, 2)))
print("Course" in globals())
def show_locals():
x, y = 1, 2
return locals()
print(show_locals())
Course True True
True False True
{'title': 'Python'} True 0
2999
False
['platform', 'title']
True True True
True
{'x': 1, 'y': 2}
eval, exec, compile and the safe alternative
import ast
print(eval("2 + 3 * 4"))
exec("result = sum(range(5))\nprint('exec result:', result)")
code = compile("x * 2", "<string>", "eval")
print(eval(code, {"x": 21}))
user_text = "[1, 2, {'a': 3}]"
print(ast.literal_eval(user_text))
try:
ast.literal_eval("__import__('os').getcwd()")
except ValueError as e:
print("literal_eval refused unsafe input")
14
exec result: 10
42
[1, 2, {'a': 3}]
literal_eval refused unsafe input
Common Mistakes
- Calling eval() or exec() on user input — a serious security vulnerability.
- Shadowing built-ins by naming variables list, dict, sum, max, id, type or input.
- Using type(x) == SomeClass instead of isinstance(x, SomeClass), which ignores subclasses.
- Forgetting that map, filter, zip, reversed and enumerate return one-shot iterators.
Key Points to Remember
- Built-ins are always available: math, conversion, iteration, introspection, I/O.
- min/max/sorted accept key functions; sum accepts start; next accepts a default.
- getattr/setattr/hasattr/delattr and vars/dir enable dynamic attribute access.
- isinstance respects inheritance; callable tests whether something can be called.
- Avoid eval/exec on untrusted input; use ast.literal_eval for literals.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.