Skip to content

Python Built-in Functions

Python provides a large collection of built-in functions (usable without any import) as well as a set of “magic method” (dunder method) protocols that allow custom classes to interoperate with built-in operators and functions.

Common Built-in Functions

Math Calculations

print(abs(-5))             # 5
print(round(3.14159, 2))   # 3.14
print(sum([1, 2, 3, 4]))   # 10
print(max(3, 1, 4, 1, 5))  # 5
print(min([3, 1, 4]))      # 1
print(pow(2, 10))          # 1024
print(divmod(17, 5))       # (3, 2) → quotient and remainder

Type Conversion

print(int("42"))           # 42
print(int("0xff", 16))     # 255 (hexadecimal string)
print(float("3.14"))       # 3.14
print(str(123))            # '123'
print(bool(0))             # False
print(list(range(5)))      # [0, 1, 2, 3, 4]
print(tuple([1, 2, 3]))    # (1, 2, 3)
print(set([1, 2, 2, 3]))   # {1, 2, 3}
print(dict(a=1, b=2))      # {'a': 1, 'b': 2}
print(bytes("hello", "utf-8"))  # b'hello'

Base Conversion

print(bin(255))   # '0b11111111' (binary)
print(oct(255))   # '0o377' (octal)
print(hex(255))   # '0xff' (hexadecimal)

# Reverse: string → integer
print(int("0b11111111", 2))   # 255
print(int("0xff", 16))        # 255

Characters and Encoding

print(ord("A"))    # 65 (character → ASCII/Unicode code point)
print(chr(65))     # 'A' (code point → character)
print(ord("中"))   # 20013
print(chr(20013))  # '中'

Sequence Operations

nums = [3, 1, 4, 1, 5, 9, 2, 6]

# sorted: returns a new list, does not modify the original
print(sorted(nums))                           # [1, 1, 2, 3, 4, 5, 6, 9]
print(sorted(nums, reverse=True))             # descending order
print(sorted(["banana", "apple"], key=len))   # sort by length

# reversed: returns an iterator
print(list(reversed(nums)))

# enumerate: iterate with index
for i, v in enumerate(["a", "b", "c"], start=1):
    print(f"{i}: {v}")

# zip: parallel iteration over multiple sequences
for name, score in zip(["Alice", "Bob"], [90, 85]):
    print(f"{name}: {score}")

# zip supports the strict parameter in Python 3.10+
# list(zip([1, 2], [1, 2, 3], strict=True))  # raises error if lengths differ

# map / filter
doubles = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

# any / all
print(any(x > 8 for x in nums))   # True
print(all(x > 0 for x in nums))   # True

Object Inspection

print(type(42))              # <class 'int'>
print(isinstance(42, int))   # True
print(isinstance(42, (int, float)))  # True (multi-type check)
print(issubclass(bool, int)) # True (bool is a subclass of int)

print(id(42))        # object memory address (CPython implementation)
print(len([1, 2, 3]))  # 3
print(hash("hello"))   # hash value

# Code execution (use with caution — security risk)
result = eval("2 + 3 * 4")   # 14
exec("x = 10; print(x)")     # execute statements

Input and Output

name = input("Enter your name: ")  # always returns a string
age = int(input("Enter your age: "))

print("Hello", "World", sep=", ", end="!\n")  # Hello, World!
print(f"Name: {name}, Age: {age}")

# repr: show the raw string representation (without escape processing)
print(repr("hello\nworld"))   # 'hello\\nworld'

Other Useful Functions

# range
for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
    print(i)

# open (file operations)
with open("file.txt", "r", encoding="utf-8") as f:
    print(f.read())

# vars / dir
print(vars())         # variable dictionary of the current scope
print(dir(str))       # list all attributes and methods of str
print(help(sorted))   # view function documentation

# iter / next (manual iteration)
it = iter([1, 2, 3])
print(next(it))  # 1
print(next(it))  # 2

Magic Methods (Dunder Methods)

Magic methods are surrounded by double underscores (__xxx__). Python calls them automatically in specific situations.

Object Lifecycle

class MyClass:
    def __new__(cls, *args, **kwargs):
        """Create the object (called before __init__). Rarely needs to be overridden."""
        print("__new__ called")
        return super().__new__(cls)

    def __init__(self, value: int):
        """Initialize the object."""
        print("__init__ called")
        self.value = value

    def __del__(self):
        """Called when the object is garbage collected. Not recommended for resource cleanup."""
        print(f"__del__ called, value={self.value}")

obj = MyClass(42)  # calls __new__ then __init__ in sequence

String Representation

class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    def __str__(self) -> str:
        """Called by print(obj) or str(obj); human-readable representation."""
        return f"({self.x}, {self.y})"

    def __repr__(self) -> str:
        """Called by repr(obj); developer-facing debug representation that should reproduce the object."""
        return f"Point(x={self.x}, y={self.y})"

p = Point(3.0, 4.0)
print(p)       # (3.0, 4.0)          → calls __str__
print(repr(p)) # Point(x=3.0, y=4.0) → calls __repr__

Operator Overloading

class Vector:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    def __add__(self, other: "Vector") -> "Vector":
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other: "Vector") -> "Vector":
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar: float) -> "Vector":
        return Vector(self.x * scalar, self.y * scalar)

    def __abs__(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Vector):
            return NotImplemented
        return self.x == other.x and self.y == other.y

    def __repr__(self) -> str:
        return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)    # Vector(4, 6)
print(abs(v2))    # 5.0
print(v1 == v1)   # True

Container Protocol

class Stack:
    def __init__(self):
        self._items: list = []

    def push(self, item) -> None:
        self._items.append(item)

    def pop(self):
        return self._items.pop()

    def __len__(self) -> int:
        """Called by len(obj)."""
        return len(self._items)

    def __contains__(self, item) -> bool:
        """Called by the in operator."""
        return item in self._items

    def __getitem__(self, index):
        """Called by obj[i]."""
        return self._items[index]

    def __iter__(self):
        """Called by for x in obj."""
        return iter(self._items)

s = Stack()
s.push(1)
s.push(2)
print(len(s))       # 2
print(1 in s)       # True
print(s[0])         # 1

Callable Objects

class Adder:
    def __init__(self, n: int):
        self.n = n

    def __call__(self, x: int) -> int:
        """Called by obj(args), making the object callable like a function."""
        return x + self.n

add5 = Adder(5)
print(add5(10))    # 15
print(callable(add5))  # True

Context Managers

class Timer:
    def __enter__(self):
        import time
        self._start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        self.elapsed = time.perf_counter() - self._start
        print(f"Elapsed: {self.elapsed:.4f}s")
        return False   # do not suppress exceptions

with Timer() as t:
    import time
    time.sleep(0.1)
# Elapsed: 0.1001s

Built-in Attributes

class Dog:
    """The Dog class."""
    species = "Canis lupus familiaris"

    def __init__(self, name: str):
        self.name = name

fido = Dog("Fido")

print(Dog.__name__)      # 'Dog'
print(Dog.__doc__)       # 'The Dog class.'
print(Dog.__dict__)      # class namespace dictionary
print(fido.__dict__)     # instance attribute dictionary {'name': 'Fido'}
print(fido.__class__)    # <class '__main__.Dog'>
print(Dog.__bases__)     # (<class 'object'>,)  tuple of direct base classes
print(Dog.__mro__)       # method resolution order
Last updated on