Python Builtin Functions: A Concise Reference

Python builtin functions

Python Built-ins Functions: A Complete Guide

Python is renowned for its simplicity, readability, and power: qualities that stem in large part from its rich set of built-in functions, values, and exceptions. These python builtin functions are preloaded into Python’s core, providing developers with ready-to-use tools for performing common tasks without needing to import external modules.

From data inspection and type conversion to iteration, mathematical operations, and error handling, Python’s built-in features empower developers to write clean, concise, and efficient code. Whether you are building simple scripts or complex applications, understanding these built-ins is essential to mastering the language.

In this guide, we provide a comprehensive reference to all 100 Python built-ins, each presented with:

  • Definition and usage — a clear explanation of what the function or exception does.
  • Syntax — the precise way to use it.
  • Parameter values — the meaning of its arguments.
  • Examples — practical code snippets to demonstrate its usage.

This resource is designed as both a learning tool for Python beginners and a quick reference for experienced developers — a single, comprehensive guide to help you leverage the full power of Python’s built-in capabilities.

By mastering these built-ins, you not only improve your programming efficiency but also elevate the quality and maintainability of your code.

Python Builtin Functions abs: absolute value of a number

Returns the absolute value of a number.

abs(x)

x: A number (integer, float, or complex).

Python
print(abs(-5.2)) # Output: 5.2 
print(abs(3 + 4j)) # Output: 5.0
Python

Python Builtin Functions aiter: asynchronous iterator adapter

Returns an asynchronous iterator for an asynchronous iterable.

aiter(async_iterable)

async_iterable: An object that supports the asynchronous iteration protocol.

Python
# An example using a simple async iterable
import nest_asyncio
nest_asyncio.apply()

async def my_async_gen():
    yield 1
    yield 2

async def main():
    async_iter = aiter(my_async_gen())
    print(await anext(async_iter)) # 1
    print(await anext(async_iter)) # 2

import asyncio
asyncio.run(main())
Python

all: True if every element is truthy

Returns True if all elements of an iterable are truthy (or if the iterable is empty), otherwise returns False.

all(iterable)

iterable: An iterable object (list, tuple, etc.).

Python
print(all([True, 1, 'hello'])) # Output: True 
print(all([True, 0, 'hello'])) # Output: False
Python

any: True if any element is truthy

Returns True if any element of an iterable is truthy, otherwise returns False.

any(iterable)

iterable: An iterable object.

Python builtin any
print(any([0, '', False, 5])) # Output: True 
print(any([0, '', False])) # Output: False
Python builtin any

anext: get next item from async iterator

Returns the next item from an asynchronous iterator.

anext(async_iterator[, default])

async_iterator: An asynchronous iterator.

default: Optional value to return if the iterator is exhausted.

Python builtin iterator
import nest_asyncio
nest_asyncio.apply()
async def gen():
    yield 'a' 
    yield 'b' 
async def main():
    it = gen() 
    print(await anext(it)) # a 
    print(await anext(it, 'c')) # b 
    print(await anext(it, 'c')) # c 

import asyncio 
asyncio.run(main())
Python builtin iterator

ascii — ASCII-only representation of an object

Returns a string containing a printable representation of an object, escaping non-ASCII characters.

ascii(object)

object: Any Python object.

print(ascii(‘Hello, 世界’)) # Output: ‘Hello, \\u4e16\\u754c’

bin: binary string of an int

Converts an integer to a binary string prefixed with “0b”.

bin(x)

x: An integer.

print(bin(10)) # Output: 0b1010

breakpoint: drop into debugger (calls sys.breakpointhook)

Drops the program into the debugger at the point of the call.

breakpoint(*args, **kwargs)

Optional arguments passed to sys.breakpointhook.

Python
def my_function():
    x = 5 
    breakpoint() 
    y = 10 # Running this will pause execution on line 3 and open a debugger prompt.
Python

bool: convert to boolean

Converts a value to a boolean, True or False.

bool(x)

x: Any object.

Python
print(bool(1)) # Output: True 
print(bool([])) # Output: False 
print(bool('hello')) # Output: True
Python

bytearray: mutable sequence of bytes

Returns a new array of bytes. It is a mutable sequence.

bytearray([source[, encoding[, errors]]])

source: Optional. An iterable of integers, a string, or an integer.

Python
b = bytearray(b'hello') 
b[0] = 72 
print(b) # Output: bytearray(b'Hello')
Python

bytes: immutable bytes sequence

Returns a new immutable sequence of bytes.

bytes([source[, encoding[, errors]]])

source: Optional. Similar to bytearray.

Python
b = bytes([72, 101, 108, 108, 111]) 
print(b) # Output: b'Hello'
Python

callable: check if object is callable

Returns True if the object appears to be callable, False otherwise.

callable(object)

object: Any object.

Python
def my_func():
    pass 
    print(callable(my_func)) # Output: True 
    print(callable(5)) # Output: False

my_func()
Python

chr: character from Unicode code point

Returns the character corresponding to an integer Unicode code point.

chr(i)

i: An integer representing a Unicode code point.

Python
print(chr(65)) # Output: 'A' 
print(chr(97)) # Output: 'a' 
print(chr(8364)) # Output: '€'
Python

classmethod: define a class method decorator

A decorator that transforms a method into a class method. The first argument of a class method is the class itself.

@classmethod

None, used as a decorator.

Python
class MyClass: 
    @classmethod
    def my_method(cls):
        return cls.__name__ 
print(MyClass.my_method()) # Output: MyClass
Python

compile: compile source to code object

Compiles a string of Python code into a code object that can be executed later using exec() or eval().

compile(source, filename, mode[, flags[, dont_inherit]])

source: The source code string. filename: A string for the filename. mode: exec, eval, or single.

Python
code = compile('x = 5\nprint(x)', '<string>', 'exec') 
exec(code) # Output: 5
Python

complex: complex number constructor

Creates a complex number or converts a string to a complex number.

complex([real[, imag]])

real: The real part. imag: The imaginary part.

Python
c1 = complex(2, 5) # 2 + 5j 
c2 = complex('1+2j') 
print(c1) # (2+5j) 
print(c2) # (1+2j)
Python

delattr: delete an attribute from an object

Deletes a named attribute from an object. delattr(obj, ‘name’) is equivalent to del obj.name.

delattr(object, name)

object: The object. name: A string with the attribute’s name.

Python
class MyClass:
    x = 5 
obj = MyClass() 
print(obj.x) #5
delattr(obj, 'x') 
print(obj.x) # This would raise an AttributeError
Python

dict: dictionary constructor / type

Creates a new dictionary object.

dict(**kwargs) or dict(mapping) or dict(iterable)

Can take keyword arguments, a dictionary, or an iterable of key-value pairs.

Python
d = dict(a=1, b=2) 
print(d) # Output: {'a': 1, 'b': 2}
Python

dir: list attributes of an object

Returns a list of names in the current local scope, or a list of attributes of an object.

dir([object])

object: Optional. An object.

Python
print(dir([])) # Output: A list of list methods like 'append', 'clear', etc. 
print(dir()) # Output: A list of names in the current scope
Python

divmod: quotient and remainder pair

Returns a pair of numbers, the quotient and the remainder, from integer division.

divmod(a, b)

a: The numerator. b: The denominator.

Python
print(divmod(10, 3)) # Output: (3, 1)
Python

enumerate: iterator of (index, value) pairs

Returns an enumerate object, which is an iterator that yields pairs of (index, value) for an iterable.

enumerate(iterable, start=0)

iterable: An iterable.

start: Optional, the starting index.

Python
l = ['a', 'b', 'c'] 
for i, item in enumerate(l):
    print(f"{i}: {item}") # Output: # 0: a # 1: b # 2: c
Python

eval — evaluate an expression (use carefully)

Parses and evaluates a Python expression from a string.

eval(expression[, globals[, locals]])

expression: A string. globals, locals: Dictionaries for the global and local scope.

Python
print(eval('3 + 5')) # Output: 8
Python

exec: execute dynamically created code

Executes a string of Python statements.

exec(object[, globals[, locals]])

object: A string or code object. globals, locals: Dictionaries.

Python
exec('x = 10\nprint(x)') # Output: 10
Python

filter: filter values by predicate (iterator)

Constructs an iterator from elements of an iterable for which a function returns true.

filter(function, iterable)

function: A function that returns a boolean.

iterable: An iterable.

Python
def is_even(n): 
    return n % 2 == 0
    
numbers = [1, 2, 3, 4, 5] 
even_numbers = list(filter(is_even, numbers)) 
print(even_numbers) # Output: [2, 4]
Python

float: float constructor

Converts an object to a floating-point number.

float([x])

x: A number or string.

Python
print(float('3.14')) # Output: 3.14
Python

format — format value with spec

Formats a value using a format specifier.

format(value[, format_spec])

value: The value to format.

format_spec: A string specifying the format.

Python
print(format(100, '0x')) # Output: 64
Python

frozenset — immutable set type

Creates an immutable set object. Elements cannot be added or removed.

frozenset([iterable])

iterable: Optional.

Python
fs = frozenset([1, 2, 3])
fs.add(4) # This would raise an AttributeError
Python

Python Builtin Functions getattr: get attribute with optional default

Returns the value of a named attribute of an object.

getattr(object, name[, default])
  • object: The object.
  • name: A string representing the attribute name.
  • default: Optional default value returned if attribute does not exist.
Python
class MyClass:
    x = 5

obj = MyClass()
print(getattr(obj, 'x'))      # Output: 5
print(getattr(obj, 'y', 10))  # Output: 10
Python

Python Builtin Functions globals: dictionary of global symbols

Returns a dictionary representing the current global symbol table.

globals()
  • None
Python
x = 10
g = globals()
print(g['x'])  # Output: 10
Python

Python Builtin Functions hasattr: test for attribute existence

Returns True if the object has the given named attribute, False otherwise.

hasattr(object, name)

  • object: The object.
  • name: The attribute name as a string.
Python
class MyClass:
    x = 5

obj = MyClass()
print(hasattr(obj, 'x'))  # Output: True
print(hasattr(obj, 'y'))  # Output: False
Python

Python Builtin Functions hash: hash value for hashable object

Returns the hash value of an object, if it has one.

Python
hash(object)
Python
  • object: A hashable object (string, number, etc.).
Python
print(hash('hello'))
print(hash(5))
Python

Python Builtin Functions help: interactive help (or doc lookup)

Invokes the built-in help system.

help([object])
  • object: Optional.
Python
help(str)   # Provides documentation for the str type
Python

Python Builtin Functions hex: hexadecimal string of an int

Converts an integer to a hexadecimal string prefixed with “0x”.

hex(x)
  • x: An integer.
Python
print(hex(255))  # Output: 0xff
Python

Python Builtin Functions id: unique identifier (object identity)

Returns the “identity” of an object. This is an integer guaranteed to be unique and constant for the lifetime of the object.

id(object)
  • object: Any object.
Python
x = [1, 2]
print(id(x))
Python

Python Builtin Functions input: read a line from stdin

Reads a line from standard input, converts it to a string, and returns it.

input([prompt])
  • prompt: Optional. A string to display before reading input.
Python
name = input("Enter your name: ")
print(f"Hello, {name}!")
Python

Python Builtin Functions int: integer constructor

Converts a number or string to an integer.

int([x[, base]])

  • x: A number or string.
  • base: Optional, the base of the number string.
Python
print(int('10', 2))  # Output: 2
Python

Python Builtin Functions isinstance: type-check instance against type(s)

Returns True if the object is an instance of the class or of a subclass thereof.

isinstance(object, classinfo)

  • object: The object.
  • classinfo: A class, tuple of classes, or union type.
Python
print(isinstance(5, int))       # Output: True
print(isinstance('hello', str)) # Output: True
Python

Python Builtin Functions issubclass: check subclass relationship

Returns True if class is a subclass of classinfo.

issubclass(class, classinfo)

  • class: A class.
  • classinfo: A class or tuple of classes.
Python
class Parent: pass
class Child(Parent): pass
print(issubclass(Child, Parent))  # Output: True
Python

Python Builtin Functions iter: get iterator from iterable

Returns an iterator object for an iterable.

iter(object[, sentinel])

  • object: An iterable.
  • sentinel: Optional, used for function-based iterators.
Python
it = iter([1, 2, 3])<br>print(next(it))  # Output: 1
Python

Python Builtin Functions len: length of a container

Returns the number of items in a container (sequence, mapping, etc.).

len(s)

  • s: A container object.
Python
print(len("hello"))  # Output: 5
Python

Python Builtin Functions list: list constructor / type

Creates a new list.

list([iterable])

  • iterable: Optional.
Python
print(list('abc'))  # Output: ['a', 'b', 'c']
Python

Python Builtin Functions locals: dictionary of local symbols

Returns a dictionary representing the current local symbol table.

locals()

  • None
Python
def my_func():
    x = 5
    print(locals()['x'])
my_func()  # Output: 5
Python

Python Builtin Functions map: apply function to each item (iterator)

Applies a function to every item of an iterable and returns a new iterator.

map(function, iterable, …)

  • function: A function.
  • iterable: One or more iterables.
Python
def square(x):
    return x * x

numbers = [1, 2, 3]
squared = list(map(square, numbers))
print(squared)  # Output: [1, 4, 9]
Python

Python Builtin Functions max: maximum value (with key support)

Returns the largest item in an iterable or the largest of two or more arguments.

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

  • iterable or arguments.
  • key: Optional function to customize comparison.
  • default: Optional value returned if iterable is empty.
Python
print(max([1, 5, 2]))           # Output: 5
print(max('apple', 'banana'))   # Output: banana
Python

Python Builtin Functions memoryview: memory view of binary object

Returns a memory view object from a given argument, allowing access to an object’s internal buffer without copying.

memoryview(obj)

  • obj: A bytes-like object.
Python
b = b'hello'
mv = memoryview(b)
print(mv[0])  # Output: 104
Python

Python Builtin Functions min: minimum value (with key support)

Returns the smallest item in an iterable or the smallest of two or more arguments.

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

  • iterable or arguments.
  • key: Optional function to customize comparison.
  • default: Optional value returned if iterable is empty.
Python
print(min([1, 5, 2]))  # Output: 1
Python

Python Builtin Functions next: advance iterator, optional default

Retrieves the next item from an iterator.

next(iterator[, default])

  • iterator: An iterator.
  • default: Optional value to return if iterator is exhausted.
Python
it = iter([1, 2])
print(next(it))  # Output: 1
print(next(it))  # Output: 2
Python

Python Builtin Functions object: base object type

The base class for all new-style classes.

object()

  • None.
Python
class MyClass(object):
    pass

print(issubclass(MyClass, object))  # Output: True
Python

Python Builtin Functions oct: octal string of an int

Converts an integer to an octal string prefixed with “0o”.

oct(x)

  • x: An integer.
Python
print(oct(8))  # Output: 0o10
Python

Python Builtin Functions open: open a file and return a file object

Opens a file and returns a corresponding file object.

open(file, mode=’r’, …)

  • file: The path to the file.
  • mode: The file open mode.
Python
with open('my_file.txt', 'w') as f:
    f.write('Hello, world!')
Python

Python Builtin Functions ord: integer code point of a single character

Returns an integer representing the Unicode code point of a character.

ord(c)

  • c: A single character string.
Python
print(ord('A'))    # Output: 65
print(ord('€'))    # Output: 8364
Python

Python Builtin Functions pow: power, optional modulo

Returns x to the power of y. If z is given, returns x**y % z.

  • x, y: Numbers.
  • z: Optional number for modulo.
Python
print(pow(2, 3))       # Output: 8
print(pow(2, 3, 5))    # Output: 3
Python

Python Builtin Functions print: print objects to stream

  • objects: The objects to print.
  • sep: Separator between objects (default is space ‘ ‘).
  • end: String appended after the last object (default is newline ‘\n’).
  • file: Output stream (default is sys.stdout).
  • flush: Boolean specifying whether to forcibly flush the stream.
Python
print('hello', 'world', sep='-')  # Output: hello-world
Python

Python Builtin Functions property: create property attribute

Returns a property attribute used to manage class attributes via methods.

  • fget: Function for getting the attribute value.
  • fset: Function for setting the attribute value.
  • fdel: Function for deleting the attribute value.
  • doc: Optional docstring.
Python
class MyClass:
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

obj = MyClass(5)
print(obj.x)  # Output: 5
Python

Python Builtin Functions range: sequence of integers (efficient)

Returns an immutable sequence object that generates a series of integers.

  • start: Starting integer (optional).
  • stop: Stop integer (exclusive).
  • step: Increment between integers (optional).
Python
for i in range(3):
    print(i)  # Outputs: 0, 1, 2
Python

Python Builtin Functions repr: developer-friendly string repr

Returns a string containing a printable representation of an object, usually valid Python code.

  • object: Any object.
Python
print(repr('hello'))  # Output: 'hello'
Python

Python Builtin Functions reversed: reverse iterator over a sequence

Returns a reverse iterator over a sequence.

  • seq: A sequence object that supports reversal.
Python
l = [1, 2, 3]<br>print(list(reversed(l)))  # Output: [3, 2, 1]
Python

Python Builtin Functions round: round a number to given digits

Rounds a number to a specified number of decimal places.

  • number: A number.
  • ndigits: Optional number of decimal places.
Python
print(round(3.14159, 2))  # Output: 3.14
Python

Python Builtin Functions set: mutable set type

Creates a new set object.

  • iterable: Optional iterable to initialize the set.
Python
s = {1, 2, 3, 3}
print(s)  # Output: {1, 2, 3}
s.add(4)
print(s)  # Output: {1, 2, 3, 4}
Python

Python Builtin Functions setattr: set attribute on an object

Sets the value of a named attribute on an object. Equivalent to obj.name = value.

  • object: The object.
  • name: The attribute name as a string.
  • value: The new value.
Python
class MyClass: pass
obj = MyClass()
setattr(obj, 'x', 5)
print(obj.x)  # Output: 5
Python

Python Builtin Functions slice: create a slice object

Returns a slice object that can be used for slicing sequences.

  • start: Starting index (optional).
  • stop: Ending index.
  • step: Step value (optional).

Python Builtin Functions sorted: return a new sorted list

Returns a new sorted list from the items in an iterable.

  • iterable: An iterable.
  • key: Optional function to extract a comparison key.
  • reverse: True for descending order (default False).
Python
l = [3, 1, 2]
print(sorted(l))  # Output: [1, 2, 3]
Python

Python Builtin Functions staticmethod: define a static method decorator

A decorator that transforms a method into a static method. It doesn’t receive an implicit first argument.

  • None (used as a decorator).
Python
class MyClass:
    @staticmethod
    def add(x, y):
        return x + y
print(MyClass.add(2, 3))  # Output: 5
Python

Python Builtin Functions str: string constructor / type

Creates a new string object.

  • object: An object to convert.
  • encoding: Encoding type (optional).
  • errors: How to handle encoding errors (optional).

Python Builtin Functions sum: sum of items (with start)

Sums the items of an iterable.

  • iterable: An iterable of numbers.
  • start: Optional value to add to the sum.
Python
print(sum([1, 2, 3]))        # Output: 6
print(sum([1, 2, 3], 10))    # Output: 16
Python

Python Builtin Functions super: proxy for parent class methods

Returns a proxy object that delegates method calls to a parent or sibling class.

  • type, object_or_type: Optional for specifying the class hierarchy.
Python
class Parent:
    def greeting(self):
        return 'Hello from Parent'

class Child(Parent):
    def greeting(self):
        return super().greeting() + ' and Child'

c = Child()
print(c.greeting())  # Output: Hello from Parent and Child
Python

Python Builtin Functions tuple: tuple constructor / type

Creates a new tuple object.

  • iterable: Optional iterable to initialize the tuple.

Python Builtin Functions type: get type or create new type

Returns the type of an object or creates a new class.

  • object: An object.
  • name, bases, dict: Used for creating a new class.

Python Builtin Functions vars: dict for an object or locals()

Returns the __dict__ attribute of a module, class, or object.

  • object: Optional.
Python
class MyClass:
    x = 5

obj = MyClass()
print(vars(obj))      # Output: {}
print(vars(MyClass))  # Output: dictionary of class attributes
Python

Python Builtin Functions zip: aggregate elements from iterables

Creates an iterator that aggregates elements from multiple iterables.

  • iterables: One or more iterables.
Python
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']
print(list(zip(l1, l2)))  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Python

Python Builtin Functions __import__: low-level import function

A low-level function that is used to implement the import statement.

  • name: Name of the module.
  • globals: Optional globals dictionary.
  • locals: Optional locals dictionary.
  • fromlist: Optional list of attributes to import.
  • level: Specifies whether to use absolute or relative imports.
Python
sys = __import__('sys')
print(sys.version_info)
Python

Python Builtin Values NotImplemented: special value used by rich comparisons

A special value that should be returned by binary special methods (like __eq__, __add__, etc.) to indicate the operation is not implemented for the other type.

  • None.
Python
class MyClass:
    def __eq__(self, other):
        if isinstance(other, int):
            return self.value == other
        return NotImplemented
Python

Python Builtin Values Ellipsis: special singleton (…) used in slicing/typing

The … syntax, used for special slicing and in type hints.

  • None.
Python
l = [[1, 2], [3, 4], [5, 6]]
print(l[...])  # Equivalent to l[:]
Python

Python Builtin Exceptions BaseException: root exception class

The base class for all built-in exceptions.

All other exceptions are subclasses of this.


Python Builtin Exceptions Exception: base class for most errors

The base class for most non-fatal exceptions.

Python
try:
    raise Exception("An error occurred")
except Exception as e:
    print(e)
Python

Python Builtin Exceptions ArithmeticError: base class for numeric errors

Base class for exceptions that occur during arithmetic calculations.

Includes exceptions like OverflowError, ZeroDivisionError.


Python Builtin Exceptions BufferError: buffer related error

Raised when a buffer-related operation cannot be performed.

Python
mv = memoryview(b"abc")
try:
    mv[0] = b'd'
except BufferError as e:
    print(e)
Python

Python Builtin Exceptions LookupError: base class for lookup errors

Base class for exceptions raised when a key or index used on a mapping or sequence is invalid.

Includes exceptions like KeyError and IndexError.


Python Builtin Exceptions AssertionError: failed assert statement

Raised when an assert statement fails.

Python
try:
    assert 1 == 2
except AssertionError as e:
    print(e)
Python

Python Builtin Exceptions AttributeError: missing attribute access error

Raised when an attribute reference or assignment fails.

Python
class MyClass:
    pass

try:
    MyClass().x
except AttributeError as e:
    print(e)
Python

Python Builtin Exceptions EOFError: end-of-file when reading input

Raised when one of the input() functions hits an end-of-file condition.


Python Builtin Exceptions FloatingPointError: floating point operation error

Raised when a floating-point operation fails. Rarely occurs.


Python Builtin Exceptions GeneratorExit: raised when generator.close() is called

Raised by a generator’s close() method to terminate the generator.

Python
def my_generator():
    try:
        yield 1
    finally:
        print("Generator closed")

gen = my_generator()
print(next(gen))
gen.close()
Python

Python Builtin Exceptions ImportError: import-related error

Raised when the import statement has trouble loading a module.

Python
try:
    import non_existent_module
except ImportError as e:
    print(e)
Python

Python Builtin Exceptions ModuleNotFoundError: module not found on import

A subclass of ImportError, raised when a module cannot be found.

Python
try:
    import non_existent_module
except ModuleNotFoundError as e:
    print(e)
Python

Python Builtin Exceptions IndexError: sequence index out of range

Raised when a sequence index is out of range.

Example of Python builtin exception IndexError

Python
l = [1, 2]
try:
    print(l[2])
except IndexError as e:
    print(e)
Python

Python Builtin Exceptions KeyError: mapping key not found

Raised when a dictionary key is not found.

Python
d = {'a': 1}
try:
    print(d['b'])
except KeyError as e:
    print(e)
Python

Python Builtin Exceptions KeyboardInterrupt: user interruption (Ctrl+C)

Raised when the user hits the interrupt key (usually Ctrl+C).

Python Builtin Exceptions MemoryError: out of memory

Raised when an operation runs out of memory.


Python Builtin Exceptions NameError: name not found in local/global scope

Raised when a local or global name is not found.

Python
try:
    print(non_existent_variable)
except NameError as e:
    print(e)
Python

Python Builtin Exceptions NotImplementedError: method abstract/not implemented

Raised when an abstract method is not implemented in a subclass.

Python
class Base:
    def my_method(self):
        raise NotImplementedError

class Sub(Base):
    pass

try:
    Sub().my_method()
except NotImplementedError as e:
    print(e)
Python

Python Builtin Exceptions OSError: OS related error (file, network, etc.)

Raised for system-related errors, such as I/O failures.


Python Builtin Exceptions OverflowError: arithmetic result too large to represent

Raised when an arithmetic operation’s result is too large to be represented.
(Note: standard integers in Python can handle arbitrary size).

Python
import math
try:
    print(math.exp(1000))
except OverflowError as e:
    print(e)
Python

Conclusion: Summary of Python Builtin Functions, Values, and Exceptions

Python’s built-in functions, values, and exceptions form the core of the language, providing essential tools for efficient programming without the need for external libraries. These built-ins span multiple categories:

  1. Utility Functions — such as getattr(), setattr(), hasattr(), len(), and type(), which enable inspection, modification, and validation of objects and their attributes. These functions help developers dynamically interact with data structures and objects.
  2. Type Constructors and Conversions — including int(), str(), list(), tuple(), set(), and dict(), which allow type conversion, creation of collections, and structured data management in an intuitive way.
  3. Iterators and Functional Tools — like iter(), next(), map(), filter(), zip(), and enumerate() which streamline sequence processing and functional programming paradigms, improving both performance and readability.
  4. Mathematical Functions — such as abs(), min(), max(), sum(), round(), pow(), and hash(), which provide efficient numeric computation and data evaluation.
  5. System and Environment Interaction — including globals(), locals(), dir(), help(), and __import__() which enable inspection of the runtime environment, dynamic module imports, and access to global and local symbol tables.
  6. Special Values — NotImplemented and Ellipsis, which serve specialized roles in object protocols and slicing operations, adding flexibility for advanced developers.
  7. Exceptions — a comprehensive set of built-in exception classes like ValueError, TypeError, AttributeError, IndexError, and KeyError, which empower robust error handling. These exception classes form the foundation for Python’s error-reporting system, enabling developers to write safer, cleaner, and more maintainable code.

Key Takeaways:

  • Python built-ins provide ease of use, speed, and consistency, allowing developers to focus on solving problems rather than reimplementing common functionality.
  • Mastery of these built-ins leads to better code quality, improved readability, and optimized performance.
  • They act as a foundational toolkit, allowing developers to build complex applications efficiently while maintaining code clarity and reliability.

In short, Python built-ins are indispensable tools that transform the way developers work — providing both power and simplicity in a single package.

Top 20 Interview Questions on Python Built-in Functions

What are Python built-in functions?

Python built-in functions are predefined functions provided by Python, available without importing any library. Examples: print(), len(), type().

How many built-in functions are available in Python 3?

Python 3.11 includes 69 built-in functions.

What is the difference between built-in and user-defined functions?

Built-in: Already provided by Python (e.g., abs(), sum()).
User-defined: Created by developers using def or lambda.

Why are built-in functions faster than user-defined ones?

Built-ins are written in C (for CPython) and optimized for speed, making them faster than equivalent Python code.

Can we override Python built-in functions?

Yes, but it’s not recommended. For example:

len = 5 print(len([1,2,3])) # Error: ‘int’ object is not callable

What does the dir() function do?

dir() returns a list of all attributes and methods of an object.

What is the difference between globals() and locals()?

globals(): Returns dictionary of current global variables.
locals(): Returns dictionary of local variables within a function.

How is eval() different from exec()?

eval(): Evaluates a Python expression and returns a result.
exec(): Executes a block of Python code but doesn’t return anything.

What does the enumerate() function do?

It adds an index to iterable elements.

for i, v in enumerate([‘a’,’b’]): print(i, v) # 0 a # 1 b

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.