
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
Definition and Usage of abs
Returns the absolute value of a number.
Syntax of abs
abs(x)
Parameter Values of abs
x: A number (integer, float, or complex).
Example of abs
print(abs(-5.2)) # Output: 5.2
print(abs(3 + 4j)) # Output: 5.0
PythonPython Builtin Functions aiter: asynchronous iterator adapter
Definition and Usage of aiter
Returns an asynchronous iterator for an asynchronous iterable.
Syntax of aiter
aiter(async_iterable)
Parameter Values of aiter
async_iterable: An object that supports the asynchronous iteration protocol.
Example of aiter
# 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())
Pythonall: True if every element is truthy
Definition and Usage of Python builtin all
Returns True if all elements of an iterable are truthy (or if the iterable is empty), otherwise returns False.
Syntax of Python builtin all
all(iterable)
Parameter Values of Python builtin all
iterable: An iterable object (list, tuple, etc.).
Example of Python builtin all
print(all([True, 1, 'hello'])) # Output: True
print(all([True, 0, 'hello'])) # Output: False
Pythonany: True if any element is truthy
Definition and Usage of Python builtin any
Returns True if any element of an iterable is truthy, otherwise returns False.
Syntax of Python builtin any
any(iterable)
Parameter Values of Python builtin any
iterable: An iterable object.
Example of Python builtin any
print(any([0, '', False, 5])) # Output: True
print(any([0, '', False])) # Output: False
Python builtin anyanext: get next item from async iterator
Definition and Usage of Python builtin iterator
Returns the next item from an asynchronous iterator.
Syntax of Python builtin iterator
anext(async_iterator[, default])
Parameter Values of Python builtin iterator
async_iterator: An asynchronous iterator.
default: Optional value to return if the iterator is exhausted.
Example of 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 iteratorascii — ASCII-only representation of an object
Definition and Usage of Python builtin ascii
Returns a string containing a printable representation of an object, escaping non-ASCII characters.
Syntax of Python builtin ascii
ascii(object)
Parameter Values of Python builtin ascii
object: Any Python object.
Example of Python builtin ascii
print(ascii(‘Hello, 世界’)) # Output: ‘Hello, \\u4e16\\u754c’
bin: binary string of an int
Definition and Usage of Python builtin bin
Converts an integer to a binary string prefixed with “0b”.
Syntax of Python builtin bin
bin(x)
Parameter Values of Python builtin bin
x: An integer.
Example of Python builtin bin
print(bin(10)) # Output: 0b1010
breakpoint: drop into debugger (calls sys.breakpointhook)
Definition and Usage of Python builtin breakpoint
Drops the program into the debugger at the point of the call.
Syntax of Python builtin breakpoint
breakpoint(*args, **kwargs)
Parameter Values of Python builtin breakpoint
Optional arguments passed to sys.breakpointhook.
Example of Python builtin breakpoint
def my_function():
x = 5
breakpoint()
y = 10 # Running this will pause execution on line 3 and open a debugger prompt.
Pythonbool: convert to boolean
Definition and Usage of Python builtin bool
Converts a value to a boolean, True or False.
Syntax of Python builtin bool
bool(x)
Parameter Values of Python builtin bool
x: Any object.
Example of Python builtin bool
print(bool(1)) # Output: True
print(bool([])) # Output: False
print(bool('hello')) # Output: True
Pythonbytearray: mutable sequence of bytes
Definition and Usage of Python builtin bytes
Returns a new array of bytes. It is a mutable sequence.
Syntax of Python builtin bytes
bytearray([source[, encoding[, errors]]])
Parameter Values of Python builtin bytes
source: Optional. An iterable of integers, a string, or an integer.
Example of Python builtin bytes
b = bytearray(b'hello')
b[0] = 72
print(b) # Output: bytearray(b'Hello')
Pythonbytes: immutable bytes sequence
Definition and Usage of Python builtin sequence
Returns a new immutable sequence of bytes.
Syntax of Python builtin sequence
bytes([source[, encoding[, errors]]])
Parameter Values of Python builtin sequence
source: Optional. Similar to bytearray.
Example of Python builtin sequence
b = bytes([72, 101, 108, 108, 111])
print(b) # Output: b'Hello'
Pythoncallable: check if object is callable
Definition and Usage of Python builtin callable
Returns True if the object appears to be callable, False otherwise.
Syntax of Python builtin callable
callable(object)
Parameter Values of Python builtin callable
object: Any object.
Example of Python builtin callable
def my_func():
pass
print(callable(my_func)) # Output: True
print(callable(5)) # Output: False
my_func()
Pythonchr: character from Unicode code point
Definition and Usage of Python builtin chr
Returns the character corresponding to an integer Unicode code point.
Syntax of Python builtin chr
chr(i)
Parameter Values of Python builtin chr
i: An integer representing a Unicode code point.
Example of Python builtin chr
print(chr(65)) # Output: 'A'
print(chr(97)) # Output: 'a'
print(chr(8364)) # Output: '€'
Pythonclassmethod: define a class method decorator
Definition and Usage of Python builtin classmethod
A decorator that transforms a method into a class method. The first argument of a class method is the class itself.
Syntax of Python builtin classmethod
@classmethod
Parameter Values of Python builtin classmethod
None, used as a decorator.
Example of Python builtin classmethod
class MyClass:
@classmethod
def my_method(cls):
return cls.__name__
print(MyClass.my_method()) # Output: MyClass
Pythoncompile: compile source to code object
Definition and Usage of Python builtin compile
Compiles a string of Python code into a code object that can be executed later using exec() or eval().
Syntax of Python builtin compile
compile(source, filename, mode[, flags[, dont_inherit]])
Parameter Values of Python builtin compile
source: The source code string. filename: A string for the filename. mode: exec, eval, or single.
Example of Python builtin compile
code = compile('x = 5\nprint(x)', '<string>', 'exec')
exec(code) # Output: 5
Pythoncomplex: complex number constructor
Definition and Usage
Creates a complex number or converts a string to a complex number.
Syntax
complex([real[, imag]])
Parameter Values
real: The real part. imag: The imaginary part.
Example
c1 = complex(2, 5) # 2 + 5j
c2 = complex('1+2j')
print(c1) # (2+5j)
print(c2) # (1+2j)
Pythondelattr: delete an attribute from an object
Definition and Usage
Deletes a named attribute from an object. delattr(obj, ‘name’) is equivalent to del obj.name.
Syntax
delattr(object, name)
Parameter Values
object: The object. name: A string with the attribute’s name.
Example
class MyClass:
x = 5
obj = MyClass()
print(obj.x) #5
delattr(obj, 'x')
print(obj.x) # This would raise an AttributeError
Pythondict: dictionary constructor / type
Definition and Usage
Creates a new dictionary object.
Syntax
dict(**kwargs) or dict(mapping) or dict(iterable)
Parameter Values
Can take keyword arguments, a dictionary, or an iterable of key-value pairs.
Example
d = dict(a=1, b=2)
print(d) # Output: {'a': 1, 'b': 2}
Pythondir: list attributes of an object
Definition and Usage
Returns a list of names in the current local scope, or a list of attributes of an object.
Syntax
dir([object])
Parameter Values
object: Optional. An object.
Example
print(dir([])) # Output: A list of list methods like 'append', 'clear', etc.
print(dir()) # Output: A list of names in the current scope
Pythondivmod: quotient and remainder pair
Definition and Usage
Returns a pair of numbers, the quotient and the remainder, from integer division.
Syntax
divmod(a, b)
Parameter Values
a: The numerator. b: The denominator.
Example
print(divmod(10, 3)) # Output: (3, 1)
Pythonenumerate: iterator of (index, value) pairs
Definition and Usage
Returns an enumerate object, which is an iterator that yields pairs of (index, value) for an iterable.
Syntax
enumerate(iterable, start=0)
Parameter Values
iterable: An iterable.
start: Optional, the starting index.
Example
l = ['a', 'b', 'c']
for i, item in enumerate(l):
print(f"{i}: {item}") # Output: # 0: a # 1: b # 2: c
Pythoneval — evaluate an expression (use carefully)
Definition and Usage
Parses and evaluates a Python expression from a string.
Syntax
eval(expression[, globals[, locals]])
Parameter Values
expression: A string. globals, locals: Dictionaries for the global and local scope.
Example
print(eval('3 + 5')) # Output: 8
Pythonexec: execute dynamically created code
Definition and Usage
Executes a string of Python statements.
Syntax
exec(object[, globals[, locals]])
Parameter Values
object: A string or code object. globals, locals: Dictionaries.
Example
exec('x = 10\nprint(x)') # Output: 10
Pythonfilter: filter values by predicate (iterator)
Definition and Usage
Constructs an iterator from elements of an iterable for which a function returns true.
Syntax
filter(function, iterable)
Parameter Values
function: A function that returns a boolean.
iterable: An iterable.
Example
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]
Pythonfloat: float constructor
Definition and Usage
Converts an object to a floating-point number.
Syntax
float([x])
Parameter Values
x: A number or string.
Example
print(float('3.14')) # Output: 3.14
Pythonformat — format value with spec
Definition and Usage of spec
Formats a value using a format specifier.
Syntax of spec
format(value[, format_spec])
Parameter Values of spec
value: The value to format.
format_spec: A string specifying the format.
Example of spec
print(format(100, '0x')) # Output: 64
Pythonfrozenset — immutable set type
Definition and Usage of frozenset
Creates an immutable set object. Elements cannot be added or removed.
Syntax of frozenset
frozenset([iterable])
Parameter Values of frozenset
iterable: Optional.
Example of frozenset
fs = frozenset([1, 2, 3])
fs.add(4) # This would raise an AttributeError
PythonPython Builtin Functions getattr: get attribute with optional default
Definition and Usage of Python builtin function getattr
Returns the value of a named attribute of an object.
Syntax of Python builtin function getattr
getattr(object, name[, default])
Parameter Values of Python builtin function getattr
- object: The object.
- name: A string representing the attribute name.
- default: Optional default value returned if attribute does not exist.
Example of Python builtin function getattr
class MyClass:
x = 5
obj = MyClass()
print(getattr(obj, 'x')) # Output: 5
print(getattr(obj, 'y', 10)) # Output: 10
PythonPython Builtin Functions globals: dictionary of global symbols
Definition and Usage of Python builtin function globals
Returns a dictionary representing the current global symbol table.
Syntax of Python builtin function globals
globals()
Parameter Values of Python builtin function globals
- None
Example of Python builtin function globals
x = 10
g = globals()
print(g['x']) # Output: 10
PythonPython Builtin Functions hasattr: test for attribute existence
Definition and Usage of Python builtin function hasattr
Returns True if the object has the given named attribute, False otherwise.
Syntax of Python builtin function hasattr
hasattr(object, name)
Parameter Values of Python builtin function hasattr
- object: The object.
- name: The attribute name as a string.
Example of Python builtin function hasattr
class MyClass:
x = 5
obj = MyClass()
print(hasattr(obj, 'x')) # Output: True
print(hasattr(obj, 'y')) # Output: False
PythonPython Builtin Functions hash: hash value for hashable object
Definition and Usage of Python builtin function hash
Returns the hash value of an object, if it has one.
Syntax of Python builtin function hash
hash(object)
PythonParameter Values of Python builtin function hash
- object: A hashable object (string, number, etc.).
Example of Python builtin function hash
print(hash('hello'))
print(hash(5))
PythonPython Builtin Functions help: interactive help (or doc lookup)
Definition and Usage of Python builtin function help
Invokes the built-in help system.
Syntax of Python builtin function help
help([object])
Parameter Values of Python builtin function help
- object: Optional.
Example of Python builtin function help
help(str) # Provides documentation for the str type
PythonPython Builtin Functions hex: hexadecimal string of an int
Definition and Usage of Python builtin function hex
Converts an integer to a hexadecimal string prefixed with “0x”.
Syntax of Python builtin function hex
hex(x)
Parameter Values of Python builtin function hex
- x: An integer.
Example of Python builtin function hex
print(hex(255)) # Output: 0xff
PythonPython Builtin Functions id: unique identifier (object identity)
Definition and Usage of Python builtin function id
Returns the “identity” of an object. This is an integer guaranteed to be unique and constant for the lifetime of the object.
Syntax of Python builtin function id
id(object)
Parameter Values of Python builtin function id
- object: Any object.
Example of Python builtin function id
x = [1, 2]
print(id(x))
PythonPython Builtin Functions input: read a line from stdin
Definition and Usage of Python builtin function input
Reads a line from standard input, converts it to a string, and returns it.
Syntax of Python builtin function input
input([prompt])
Parameter Values of Python builtin function input
- prompt: Optional. A string to display before reading input.
Example of Python builtin function input
name = input("Enter your name: ")
print(f"Hello, {name}!")
PythonPython Builtin Functions int: integer constructor
Definition and Usage of Python builtin function int
Converts a number or string to an integer.
Syntax of Python builtin function int
int([x[, base]])
Parameter Values of Python builtin function int
- x: A number or string.
- base: Optional, the base of the number string.
Example of Python builtin function int
print(int('10', 2)) # Output: 2
PythonPython Builtin Functions isinstance: type-check instance against type(s)
Definition and Usage of Python builtin function isinstance
Returns True if the object is an instance of the class or of a subclass thereof.
Syntax of Python builtin function isinstance
isinstance(object, classinfo)
Parameter Values of Python builtin function isinstance
- object: The object.
- classinfo: A class, tuple of classes, or union type.
Example of Python builtin function isinstance
print(isinstance(5, int)) # Output: True
print(isinstance('hello', str)) # Output: True
PythonPython Builtin Functions issubclass: check subclass relationship
Definition and Usage of Python builtin function issubclass
Returns True if class is a subclass of classinfo.
Syntax of Python builtin function issubclass
issubclass(class, classinfo)
Parameter Values of Python builtin function issubclass
- class: A class.
- classinfo: A class or tuple of classes.
Example of Python builtin function issubclass
class Parent: pass
class Child(Parent): pass
print(issubclass(Child, Parent)) # Output: True
PythonPython Builtin Functions iter: get iterator from iterable
Definition and Usage of Python builtin function iter
Returns an iterator object for an iterable.
Syntax of Python builtin function iter
iter(object[, sentinel])
Parameter Values of Python builtin function iter
- object: An iterable.
- sentinel: Optional, used for function-based iterators.
Example of Python builtin function iter
it = iter([1, 2, 3])<br>print(next(it)) # Output: 1
PythonPython Builtin Functions len: length of a container
Definition and Usage of Python builtin function len
Returns the number of items in a container (sequence, mapping, etc.).
Syntax of Python builtin function len
len(s)
Parameter Values of Python builtin function len
- s: A container object.
Example of Python builtin function len
print(len("hello")) # Output: 5
PythonPython Builtin Functions list: list constructor / type
Definition and Usage of Python builtin function list
Creates a new list.
Syntax of Python builtin function list
list([iterable])
Parameter Values of Python builtin function list
- iterable: Optional.
Example of Python builtin function list
print(list('abc')) # Output: ['a', 'b', 'c']
PythonPython Builtin Functions locals: dictionary of local symbols
Definition and Usage of Python builtin function locals
Returns a dictionary representing the current local symbol table.
Syntax of Python builtin function locals
locals()
Parameter Values of Python builtin function locals
- None
Example of Python builtin function locals
def my_func():
x = 5
print(locals()['x'])
my_func() # Output: 5
PythonPython Builtin Functions map: apply function to each item (iterator)
Definition and Usage of Python builtin function map
Applies a function to every item of an iterable and returns a new iterator.
Syntax of Python builtin function map
map(function, iterable, …)
Parameter Values of Python builtin function map
- function: A function.
- iterable: One or more iterables.
Example of Python builtin function map
def square(x):
return x * x
numbers = [1, 2, 3]
squared = list(map(square, numbers))
print(squared) # Output: [1, 4, 9]
PythonPython Builtin Functions max: maximum value (with key support)
Definition and Usage of Python builtin function max
Returns the largest item in an iterable or the largest of two or more arguments.
Syntax of Python builtin function max
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Parameter Values of Python builtin function max
- iterable or arguments.
- key: Optional function to customize comparison.
- default: Optional value returned if iterable is empty.
Example of Python builtin function max
print(max([1, 5, 2])) # Output: 5
print(max('apple', 'banana')) # Output: banana
PythonPython Builtin Functions memoryview: memory view of binary object
Definition and Usage of Python builtin function memoryview
Returns a memory view object from a given argument, allowing access to an object’s internal buffer without copying.
Syntax of Python builtin function memoryview
memoryview(obj)
Parameter Values of Python builtin function memoryview
- obj: A bytes-like object.
Example of Python builtin function memoryview
b = b'hello'
mv = memoryview(b)
print(mv[0]) # Output: 104
PythonPython Builtin Functions min: minimum value (with key support)
Definition and Usage of Python builtin function min
Returns the smallest item in an iterable or the smallest of two or more arguments.
Syntax of Python builtin function min
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])
Parameter Values of Python builtin function min
- iterable or arguments.
- key: Optional function to customize comparison.
- default: Optional value returned if iterable is empty.
Example of Python builtin function min
print(min([1, 5, 2])) # Output: 1
PythonPython Builtin Functions next: advance iterator, optional default
Definition and Usage of Python builtin function next
Retrieves the next item from an iterator.
Syntax of Python builtin function next
next(iterator[, default])
Parameter Values of Python builtin function next
- iterator: An iterator.
- default: Optional value to return if iterator is exhausted.
Example of Python builtin function next
it = iter([1, 2])
print(next(it)) # Output: 1
print(next(it)) # Output: 2
PythonPython Builtin Functions object: base object type
Definition and Usage of Python builtin function object
The base class for all new-style classes.
Syntax of Python builtin function object
object()
Parameter Values of Python builtin function object
- None.
Example of Python builtin function object
class MyClass(object):
pass
print(issubclass(MyClass, object)) # Output: True
PythonPython Builtin Functions oct: octal string of an int
Definition and Usage of Python builtin function oct
Converts an integer to an octal string prefixed with “0o”.
Syntax of Python builtin function oct
oct(x)
Parameter Values of Python builtin function oct
- x: An integer.
Example of Python builtin function oct
print(oct(8)) # Output: 0o10
PythonPython Builtin Functions open: open a file and return a file object
Definition and Usage of Python builtin function open
Opens a file and returns a corresponding file object.
Syntax of Python builtin function open
open(file, mode=’r’, …)
Parameter Values of Python builtin function open
- file: The path to the file.
- mode: The file open mode.
Example of Python builtin function open
with open('my_file.txt', 'w') as f:
f.write('Hello, world!')
PythonPython Builtin Functions ord: integer code point of a single character
Definition and Usage of Python builtin function ord
Returns an integer representing the Unicode code point of a character.
Syntax of Python builtin function ord
ord(c)
Parameter Values of Python builtin function ord
- c: A single character string.
Example of Python builtin function ord
print(ord('A')) # Output: 65
print(ord('€')) # Output: 8364
PythonPython Builtin Functions pow: power, optional modulo
Definition and Usage of Python builtin function pow
Returns x to the power of y. If z is given, returns x**y % z.
Syntax of Python builtin function pow
Parameter Values of Python builtin function pow
- x, y: Numbers.
- z: Optional number for modulo.
Example of Python builtin function pow
print(pow(2, 3)) # Output: 8
print(pow(2, 3, 5)) # Output: 3
PythonPython Builtin Functions print: print objects to stream
Definition and Usage of Python builtin function print
Prints objects to the text stream file, separated by sep and followed by end.
Syntax of Python builtin function print
Parameter Values of Python builtin function print
- 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.
Example of Python builtin function print
print('hello', 'world', sep='-') # Output: hello-world
PythonPython Builtin Functions property: create property attribute
Definition and Usage of Python builtin function property
Returns a property attribute used to manage class attributes via methods.
Syntax of Python builtin function property
Parameter Values of Python builtin function property
- fget: Function for getting the attribute value.
- fset: Function for setting the attribute value.
- fdel: Function for deleting the attribute value.
- doc: Optional docstring.
Example of Python builtin function property
class MyClass:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
obj = MyClass(5)
print(obj.x) # Output: 5
PythonPython Builtin Functions range: sequence of integers (efficient)
Definition and Usage of Python builtin function range
Returns an immutable sequence object that generates a series of integers.
Syntax of Python builtin function range
Parameter Values of Python builtin function range
- start: Starting integer (optional).
- stop: Stop integer (exclusive).
- step: Increment between integers (optional).
Example of Python builtin function range
for i in range(3):
print(i) # Outputs: 0, 1, 2
PythonPython Builtin Functions repr: developer-friendly string repr
Definition and Usage of Python builtin function repr
Returns a string containing a printable representation of an object, usually valid Python code.
Syntax of Python builtin function repr
Parameter Values of Python builtin function repr
- object: Any object.
Example of Python builtin function repr
print(repr('hello')) # Output: 'hello'
PythonPython Builtin Functions reversed: reverse iterator over a sequence
Definition and Usage of Python builtin function reversed
Returns a reverse iterator over a sequence.
Syntax of Python builtin function reversed
Parameter Values of Python builtin function reversed
- seq: A sequence object that supports reversal.
Example of Python builtin function reversed
l = [1, 2, 3]<br>print(list(reversed(l))) # Output: [3, 2, 1]
PythonPython Builtin Functions round: round a number to given digits
Definition and Usage of Python builtin function round
Rounds a number to a specified number of decimal places.
Syntax of Python builtin function round
Parameter Values of Python builtin function round
- number: A number.
- ndigits: Optional number of decimal places.
Example of Python builtin function round
print(round(3.14159, 2)) # Output: 3.14
PythonPython Builtin Functions set: mutable set type
Definition and Usage of Python builtin function set
Creates a new set object.
Syntax of Python builtin function set
Parameter Values of Python builtin function set
- iterable: Optional iterable to initialize the set.
Example of Python builtin function set
s = {1, 2, 3, 3}
print(s) # Output: {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
PythonPython Builtin Functions setattr: set attribute on an object
Definition and Usage of Python builtin function setattr
Sets the value of a named attribute on an object. Equivalent to obj.name = value.
Syntax of Python builtin function setattr
Parameter Values of Python builtin function setattr
- object: The object.
- name: The attribute name as a string.
- value: The new value.
Example of Python builtin function setattr
class MyClass: pass
obj = MyClass()
setattr(obj, 'x', 5)
print(obj.x) # Output: 5
PythonPython Builtin Functions slice: create a slice object
Definition and Usage of Python builtin function slice
Returns a slice object that can be used for slicing sequences.
Syntax of Python builtin function slice
Parameter Values of Python builtin function slice
- start: Starting index (optional).
- stop: Ending index.
- step: Step value (optional).
Example of Python builtin function slice
Python Builtin Functions sorted: return a new sorted list
Definition and Usage of Python builtin function sorted
Returns a new sorted list from the items in an iterable.
Syntax of Python builtin function sorted
Parameter Values of Python builtin function sorted
- iterable: An iterable.
- key: Optional function to extract a comparison key.
- reverse: True for descending order (default False).
Example of Python builtin function sorted
l = [3, 1, 2]
print(sorted(l)) # Output: [1, 2, 3]
PythonPython Builtin Functions staticmethod: define a static method decorator
Definition and Usage of Python builtin function staticmethod
A decorator that transforms a method into a static method. It doesn’t receive an implicit first argument.
Syntax of Python builtin function staticmethod
Parameter Values of Python builtin function staticmethod
- None (used as a decorator).
Example of Python builtin function staticmethod
class MyClass:
@staticmethod
def add(x, y):
return x + y
print(MyClass.add(2, 3)) # Output: 5
PythonPython Builtin Functions str: string constructor / type
Definition and Usage of Python builtin function str
Creates a new string object.
Syntax of Python builtin function str
Parameter Values of Python builtin function str
- object: An object to convert.
- encoding: Encoding type (optional).
- errors: How to handle encoding errors (optional).
Example of Python builtin function str
Python Builtin Functions sum: sum of items (with start)
Definition and Usage of Python builtin function sum
Sums the items of an iterable.
Syntax of Python builtin function sum
Parameter Values of Python builtin function sum
- iterable: An iterable of numbers.
- start: Optional value to add to the sum.
Example of Python builtin function sum
print(sum([1, 2, 3])) # Output: 6
print(sum([1, 2, 3], 10)) # Output: 16
PythonPython Builtin Functions super: proxy for parent class methods
Definition and Usage of Python builtin function super
Returns a proxy object that delegates method calls to a parent or sibling class.
Syntax of Python builtin function super
Parameter Values of Python builtin function super
- type, object_or_type: Optional for specifying the class hierarchy.
Example of Python builtin function super
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
PythonPython Builtin Functions tuple: tuple constructor / type
Definition and Usage of Python builtin function tuple
Creates a new tuple object.
Syntax of Python builtin function tuple
Parameter Values of Python builtin function tuple
- iterable: Optional iterable to initialize the tuple.
Example of Python builtin function tuple
Python Builtin Functions type: get type or create new type
Definition and Usage of Python builtin function type
Returns the type of an object or creates a new class.
Syntax of Python builtin function type
Parameter Values of Python builtin function type
- object: An object.
- name, bases, dict: Used for creating a new class.
Example of Python builtin function type
Python Builtin Functions vars: dict for an object or locals()
Definition and Usage of Python builtin function vars
Returns the __dict__ attribute of a module, class, or object.
Syntax of Python builtin function vars
Parameter Values of Python builtin function vars
- object: Optional.
Example of Python builtin function vars
class MyClass:
x = 5
obj = MyClass()
print(vars(obj)) # Output: {}
print(vars(MyClass)) # Output: dictionary of class attributes
PythonPython Builtin Functions zip: aggregate elements from iterables
Definition and Usage of Python builtin function zip
Creates an iterator that aggregates elements from multiple iterables.
Syntax of Python builtin function zip
Parameter Values of Python builtin function zip
- iterables: One or more iterables.
Example of Python builtin function zip
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']
print(list(zip(l1, l2))) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
PythonPython Builtin Functions __import__: low-level import function
Definition and Usage of Python builtin function __import__
A low-level function that is used to implement the import statement.
Syntax of Python builtin function __import__
Parameter Values of Python builtin function __import__
- 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.
Example of Python builtin function __import__
sys = __import__('sys')
print(sys.version_info)
PythonPython Builtin Values NotImplemented: special value used by rich comparisons
Definition and Usage of Python builtin value NotImplemented
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.
Syntax of Python builtin value NotImplemented
Parameter Values of Python builtin value NotImplemented
- None.
Example of Python builtin value NotImplemented
class MyClass:
def __eq__(self, other):
if isinstance(other, int):
return self.value == other
return NotImplemented
PythonPython Builtin Values Ellipsis: special singleton (…) used in slicing/typing
Definition and Usage of Python builtin value Ellipsis
The … syntax, used for special slicing and in type hints.
Syntax of Python builtin value Ellipsis
Parameter Values of Python builtin value Ellipsis
- None.
Example of Python builtin value Ellipsis
l = [[1, 2], [3, 4], [5, 6]]
print(l[...]) # Equivalent to l[:]
PythonPython Builtin Exceptions BaseException: root exception class
Definition and Usage of Python builtin exception BaseException
The base class for all built-in exceptions.
Syntax of Python builtin exception BaseException
Example of Python builtin exception BaseException
All other exceptions are subclasses of this.
Python Builtin Exceptions Exception: base class for most errors
Definition and Usage of Python builtin exception Exception
The base class for most non-fatal exceptions.
Syntax of Python builtin exception Exception
Example of Python builtin exception Exception
try:
raise Exception("An error occurred")
except Exception as e:
print(e)
PythonPython Builtin Exceptions ArithmeticError: base class for numeric errors
Definition and Usage of Python builtin exception ArithmeticError
Base class for exceptions that occur during arithmetic calculations.
Syntax of Python builtin exception ArithmeticError
Example of Python builtin exception ArithmeticError
Includes exceptions like OverflowError, ZeroDivisionError.
Python Builtin Exceptions BufferError: buffer related error
Definition and Usage of Python builtin exception BufferError
Raised when a buffer-related operation cannot be performed.
Syntax of Python builtin exception BufferError
Example of Python builtin exception BufferError
mv = memoryview(b"abc")
try:
mv[0] = b'd'
except BufferError as e:
print(e)
PythonPython Builtin Exceptions LookupError: base class for lookup errors
Definition and Usage of Python builtin exception LookupError
Base class for exceptions raised when a key or index used on a mapping or sequence is invalid.
Syntax of Python builtin exception LookupError
Example of Python builtin exception LookupError
Includes exceptions like KeyError and IndexError.
Python Builtin Exceptions AssertionError: failed assert statement
Definition and Usage of Python builtin exception AssertionError
Raised when an assert statement fails.
Syntax of Python builtin exception AssertionError
Example of Python builtin exception AssertionError
try:
assert 1 == 2
except AssertionError as e:
print(e)
PythonPython Builtin Exceptions AttributeError: missing attribute access error
Definition and Usage of Python builtin exception AttributeError
Raised when an attribute reference or assignment fails.
Syntax of Python builtin exception AttributeError
Example of Python builtin exception AttributeError
class MyClass:
pass
try:
MyClass().x
except AttributeError as e:
print(e)
PythonPython Builtin Exceptions EOFError: end-of-file when reading input
Definition and Usage of Python builtin exception EOFError
Raised when one of the input() functions hits an end-of-file condition.
Syntax of Python builtin exception EOFError
Example of Python builtin exception EOFError
Python Builtin Exceptions FloatingPointError: floating point operation error
Definition and Usage of Python builtin exception FloatingPointError
Raised when a floating-point operation fails. Rarely occurs.
Syntax of Python builtin exception FloatingPointError
Example of Python builtin exception FloatingPointError
Python Builtin Exceptions GeneratorExit: raised when generator.close() is called
Definition and Usage of Python builtin exception GeneratorExit
Raised by a generator’s close() method to terminate the generator.
Syntax of Python builtin exception GeneratorExit
Example of Python builtin exception GeneratorExit
def my_generator():
try:
yield 1
finally:
print("Generator closed")
gen = my_generator()
print(next(gen))
gen.close()
PythonPython Builtin Exceptions ImportError: import-related error
Definition and Usage of Python builtin exception ImportError
Raised when the import statement has trouble loading a module.
Syntax of Python builtin exception ImportError
Example of Python builtin exception ImportError
try:
import non_existent_module
except ImportError as e:
print(e)
PythonPython Builtin Exceptions ModuleNotFoundError: module not found on import
Definition and Usage of Python builtin exception ModuleNotFoundError
A subclass of ImportError, raised when a module cannot be found.
Syntax of Python builtin exception ModuleNotFoundError
Example of Python builtin exception ModuleNotFoundError
try:
import non_existent_module
except ModuleNotFoundError as e:
print(e)
PythonPython Builtin Exceptions IndexError: sequence index out of range
Definition and Usage of Python builtin exception IndexError
Raised when a sequence index is out of range.
Syntax of Python builtin exception IndexError
Example of Python builtin exception IndexError
l = [1, 2]
try:
print(l[2])
except IndexError as e:
print(e)
PythonPython Builtin Exceptions KeyError: mapping key not found
Definition and Usage of Python builtin exception KeyError
Raised when a dictionary key is not found.
Syntax of Python builtin exception KeyError
Example of Python builtin exception KeyError
d = {'a': 1}
try:
print(d['b'])
except KeyError as e:
print(e)
PythonPython Builtin Exceptions KeyboardInterrupt: user interruption (Ctrl+C)
Definition and Usage of Python builtin exception KeyboardInterrupt
Raised when the user hits the interrupt key (usually Ctrl+C).
Syntax of Python builtin exception KeyboardInterrupt
Example of Python builtin exception KeyboardInterrupt
Python Builtin Exceptions MemoryError: out of memory
Definition and Usage of Python builtin exception MemoryError
Raised when an operation runs out of memory.
Syntax of Python builtin exception MemoryError
Example of Python builtin exception MemoryError
Python Builtin Exceptions NameError: name not found in local/global scope
Definition and Usage of Python builtin exception NameError
Raised when a local or global name is not found.
Syntax of Python builtin exception NameError
Example of Python builtin exception NameError
try:
print(non_existent_variable)
except NameError as e:
print(e)
PythonPython Builtin Exceptions NotImplementedError: method abstract/not implemented
Definition and Usage of Python builtin exception NotImplementedError
Raised when an abstract method is not implemented in a subclass.
Syntax of Python builtin exception NotImplementedError
Example of Python builtin exception NotImplementedError
class Base:
def my_method(self):
raise NotImplementedError
class Sub(Base):
pass
try:
Sub().my_method()
except NotImplementedError as e:
print(e)
PythonPython Builtin Exceptions OSError: OS related error (file, network, etc.)
Definition and Usage of Python builtin exception OSError
Raised for system-related errors, such as I/O failures.
Syntax of Python builtin exception OSError
Example of Python builtin exception OSError
Python Builtin Exceptions OverflowError: arithmetic result too large to represent
Definition and Usage of Python builtin exception OverflowError
Raised when an arithmetic operation’s result is too large to be represented.
(Note: standard integers in Python can handle arbitrary size).
Syntax of Python builtin exception OverflowError
Example of Python builtin exception OverflowError
import math
try:
print(math.exp(1000))
except OverflowError as e:
print(e)
PythonConclusion: 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:
- 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.
- 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.
- 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.
- Mathematical Functions — such as abs(), min(), max(), sum(), round(), pow(), and hash(), which provide efficient numeric computation and data evaluation.
- 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.
- Special Values — NotImplemented and Ellipsis, which serve specialized roles in object protocols and slicing operations, adding flexibility for advanced developers.
- 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
Python built-in functions are predefined functions provided by Python, available without importing any library. Examples: print(), len(), type().
Python 3.11 includes 69 built-in functions.
Built-in: Already provided by Python (e.g., abs(), sum()).
User-defined: Created by developers using def or lambda.
Built-ins are written in C (for CPython) and optimized for speed, making them faster than equivalent Python code.
Yes, but it’s not recommended. For example:
len = 5 print(len([1,2,3])) # Error: ‘int’ object is not callable
dir() returns a list of all attributes and methods of an object.
globals(): Returns dictionary of current global variables.
locals(): Returns dictionary of local variables within a function.
eval(): Evaluates a Python expression and returns a result.
exec(): Executes a block of Python code but doesn’t return anything.
It adds an index to iterable elements.
for i, v in enumerate([‘a’,’b’]): print(i, v) # 0 a # 1 b