Course topics

By WebNest Studio Engineering Team

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.

Why it matters

Python comes with about seventy built-in functions that are always available without an import. Knowing them means not writing loops for things like the largest value, a total, or whether any item matches a condition. Experienced Python programmers reach for these first, and code that uses them is shorter and has fewer bugs.

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

Python
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))
Output
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

Python
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__)
Output
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

Python
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)
Output
[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

Python
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())
Output
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

Python
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")
Output
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.

Exercise

Using only built-in functions, print the highest and lowest score on one line, the average rounded to one decimal place, the scores sorted from high to low, and whether any score is below 60.

Expected output: 95 58, 76.5, [95, 81, 72, 58], True (one per line)

Python · starter code
scores = [72, 95, 58, 81]

# TODO: print the highest and the lowest score
# TODO: print the average, rounded to one decimal place
# TODO: print the scores sorted from high to low
# TODO: print whether any score is below 60
Show hints
  • The average is sum(scores) / len(scores), and round(value, 1) keeps one decimal.
  • any(score < 60 for score in scores) is true if at least one score matches.
Show solution
Python · solution
scores = [72, 95, 58, 81]

print(max(scores), min(scores))
print(round(sum(scores) / len(scores), 1))
print(sorted(scores, reverse=True))
print(any(score < 60 for score in scores))

Quick quiz

1. What does divmod(7, 2) return?

  • A. (3, 1)
  • B. 3.5
  • C. [3, 1]
  • D. 3
Show answer

A. It returns the quotient and the remainder together as a tuple.

2. What does list(zip("ab", [1, 2])) produce?

  • A. ['a1', 'b2']
  • B. [('a', 1), ('b', 2)]
  • C. [('a', 'b'), (1, 2)]
  • D. ['a', 'b', 1, 2]
Show answer

B. zip pairs the items that are in the same position.

3. Why should eval() not be used on text typed by a user?

  • A. It is slow
  • B. It only works on numbers
  • C. It runs the text as Python code, so the user could execute anything
  • D. It is deprecated
Show answer

C. To convert text containing a Python literal safely, use ast.literal_eval.

Interview questions

What do enumerate() and zip() do?

Show answer

enumerate(iterable) yields pairs of an index and an item, so a loop has the position without a separate counter; start=1 changes the first index. zip(a, b) yields tuples made of the items at the same position in each iterable, and stops at the shortest. Both are lazy and are normally used directly in a for loop.

What is the difference between eval() and ast.literal_eval()?

Show answer

eval() evaluates any Python expression in the string, including function calls, so with untrusted input it can run harmful code. ast.literal_eval() accepts only literals — numbers, strings, lists, tuples, dictionaries, sets, booleans and None — and raises an error for anything else, which makes it safe for turning text into data.

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 in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering