Python Built-in Functions
Python provides over 70 built-in functions that are always available without importing. Here's a practical guide organised by category.
Contents
Type conversion functions
These functions convert values between different types.
Example 1
# Numeric conversions
print(int(3.14))
>>> 3
print(float(42))
>>> 42.0
print(complex(2, 3))
>>> (2+3j)
# Collection conversions
print(list((1, 2, 3)))
>>> [1, 2, 3]
print(tuple([1, 2, 3]))
>>> (1, 2, 3)
print(dict([('a', 1), ('b', 2)]))
>>> {'a': 1, 'b': 2}
print(set([1, 2, 2, 3]))
>>> {1, 2, 3}
print(frozenset([1, 2, 3]))
>>> frozenset({1, 2, 3})
# String and bytes
print(str(42))
>>> 42
print(bytes([65, 66, 67]))
>>> b'ABC'
print(bytearray([65, 66, 67]))
>>> bytearray(b'ABC')
print(bool(1))
>>> True
print(bool(0))
>>> False
Mathematical functions
Functions for mathematical operations and comparisons.
Example 2
# Absolute value
print(abs(-5))
>>> 5
# Power
print(pow(2, 3))
>>> 8
# Summation
print(sum([1, 2, 3, 4]))
>>> 10
# Min and max
print(min(3, 1, 4, 1, 5))
>>> 1
print(max(3, 1, 4, 1, 5))
>>> 5
# Rounding
print(round(3.14159, 2))
>>> 3.14
# Division and modulo
print(divmod(17, 5))
>>> (3, 2)
Sequence operations
Functions for working with sequences like lists, tuples, and strings.
Example 3
# Length
print(len([1, 2, 3, 4, 5]))
>>> 5
# Sorting
print(sorted([3, 1, 4, 1, 5, 9, 2, 6]))
>>> [1, 1, 2, 3, 4, 5, 6, 9]
# Reversing
print(list(reversed([1, 2, 3, 4])))
>>> [4, 3, 2, 1]
# Enumerating
print(list(enumerate(['a', 'b', 'c'])))
>>> [(0, 'a'), (1, 'b'), (2, 'c')]
# Zipping
print(list(zip([1, 2, 3], ['a', 'b', 'c'])))
>>> [(1, 'a'), (2, 'b'), (3, 'c')]
# Range
print(list(range(5)))
>>> [0, 1, 2, 3, 4]
print(list(range(2, 8, 2)))
>>> [2, 4, 6]
# All and any
print(all([True, True, False]))
>>> False
print(any([False, False, True]))
>>> True
String operations
Functions for character and string manipulation.
Example 4
# Character to code point
print(ord('A'))
>>> 65
# Code point to character
print(chr(65))
>>> A
# ASCII representation
print(ascii('café'))
>>> 'caf\xe9'
# Formatting
print(format(3.14159, '.2f'))
>>> 3.14
print(format(42, 'b'))
>>> 101010
Object introspection
Functions for examining objects and their properties.
Example 5
# Type checking
print(type(42))
>>> <class 'int'>
print(isinstance(42, int))
>>> True
print(issubclass(int, object))
>>> True
# Object identity
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a) == id(b))
>>> False
# Object attributes
print(dir([]))
>>> ['__add__', '__class__', ...]
# Callable check
print(callable(len))
>>> True
print(callable(42))
>>> False
# Hash
print(hash('hello'))
>>> 99162322
Input and output
Functions for reading input and displaying output.
Example 6
# Print
print("Hello", "World", sep=", ", end="!\n")
>>> Hello, World!
# Input (commented out as it requires user interaction)
# name = input("Enter your name: ")
# Open file
# with open('file.txt', 'r') as f:
# content = f.read()
Functional programming
Functions that work with other functions for functional programming patterns.
Example 7
# Map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
>>> [1, 4, 9, 16, 25]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
>>> [2, 4]
# Iterator
iter_obj = iter([1, 2, 3])
print(next(iter_obj))
>>> 1
print(next(iter_obj))
>>> 2
# Async iterator
import asyncio
async def async_gen():
for i in range(3):
yield i
# aiter() and anext() for async iteration
Attribute operations
Functions for dynamically accessing and modifying object attributes.
Example 8
class Person:
def __init__(self, name):
self.name = name
person = Person("Alice")
# Get attribute
print(getattr(person, 'name'))
>>> Alice
print(getattr(person, 'age', 0))
>>> 0
# Set attribute
setattr(person, 'age', 30)
print(person.age)
>>> 30
# Check attribute
print(hasattr(person, 'name'))
>>> True
print(hasattr(person, 'email'))
>>> False
# Delete attribute
delattr(person, 'age')
print(hasattr(person, 'age'))
>>> False
Class operations
Functions for working with classes and methods.
Example 9
class MyClass:
@classmethod
def class_method(cls):
return "Class method"
@staticmethod
def static_method():
return "Static method"
@property
def prop(self):
return "Property"
# classmethod() and staticmethod() are decorators
# property() creates property descriptors
Other useful functions
Additional built-in functions for various purposes.
Example 10
# Binary, octal, hexadecimal
print(bin(42))
>>> 0b101010
print(oct(42))
>>> 0o52
print(hex(42))
>>> 0x2a
# Compile and execute
code = compile('print("Hello")', '<string>', 'exec')
exec(code)
>>> Hello
result = eval('2 + 3')
print(result)
>>> 5
# Variables
print(vars(person))
>>> {'name': 'Alice'}
# Globals and locals
print('len' in globals())
>>> True
# Memory view
arr = bytearray([65, 66, 67])
mv = memoryview(arr)
print(mv[0])
>>> 65
# Slice
s = slice(1, 5, 2)
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[s])
>>> [1, 3]
# Repr
print(repr('hello\n'))
>>> 'hello\n'
# Help
# help(len) # Shows help documentation
# Breakpoint
# breakpoint() # Enters debugger
# Object
obj = object()
print(type(obj))
>>> <class 'object'>