The complete Python Built-in Functions Reference: 75 functions with examples
Python offers a rich set of built-in functions that are available without the need to import additional modules. These functions are the foundation of the language and greatly simplify development. In this detailed guide, we will look at all 75 basic built-in Python functions with practical examples and explanations.
Categories of built-in functions
Input-output and display functions
1. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The main function for displaying information on the screen. Supports a variety of formatting settings.:
print("Hello, world!")
print("Name:", "Anna", "Age:", 25, sep=" | ")
print("Download", end="...")
print("completed!")
2. input(prompt="")
Gets a string from the user via standard input:
name = input("Enter your name:")
age = int(input("Enter your age:"))
print(f"Hello, {name}! You are {age} years old.")
Tip: Always use type conversion for numeric data, as input() returns a string.
Functions for working with sequences
3. len(s)
Returns the number of elements in the object:
my_list = [1, 2, 3, 4, 5]
my_string = "Python"
my_dict = {"a": 1, "b": 2}
print(len(my_list)) # 5
print(len(my_string)) # 6
print(len(my_dict)) # 2
4. range(start, stop, step)
Creates a sequence of numbers, often used in loops:
# Various use cases
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
5. enumerate(iterable, start=0)
Adds a counter to the iterated object:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# Will output: 1. apple, 2. banana, 3. cherry
6. zip(*iterables)
Combines elements of several iterable objects:
names = ['Anna', 'Boris', 'Vera']
ages = [25, 30, 35]
cities = ['Moscow', 'St. Petersburg', 'Kazan']
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age} years old, lives in {city}")
Mathematical functions
7. abs(x)
Returns the absolute value of a number:
print(abs(-7)) # 7
print(abs(3.14)) # 3.14
print(abs(-5+3j)) # 5.830951894845301 (for complex numbers)
8. sum(iterable, start=0)
Summarizes the elements of the iterated object:
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # 15
print(sum(numbers, 10)) # 25 (initial value of 10)
9. max(iterable) / max(arg1, arg2, *args)
Finds the largest element:
print(max([1, 5, 3, 9, 2])) # 9
print(max(1, 5, 3, 9, 2)) # 9
print(max(['apple', 'banana', 'cherry'])) # 'cherry' (lexicographically)
10. min(iterable) / min(arg1, arg2, *args)
Finds the smallest element:
print(min([1, 5, 3, 9, 2])) # 1
print(min('hello')) # 'e' (minimum character)
11. round(number, ndigits=None)
Rounds the number to the specified number of digits:
print(round(3.14159)) # 3
print(round(3.14159, 2)) # 3.14
print(round(1234.5, -1)) # 1230.0
12. pow(base, exp, mod=None)
Raises a number to a power:
print(pow(2, 3)) # 8
print(pow(2, 3, 5)) # 3 (2^3 % 5)
print(pow(4, 0.5)) # 2.0 (square root)
13. divmod(a, b)
Returns the quotient and remainder of the division:
quotient, remainder = divmod(17, 5)
print(f"17 ÷ 5 = {quotient} remainder {remainder}") # 17 ÷ 5 = 3 remainder 2
Type conversion functions
14. str(object)
Converts an object to a string:
print(str(123)) # '123'
print(str([1, 2, 3])) # '[1, 2, 3]'
print(str(True)) # 'True'
15. int(x, base=10)
Converts it to an integer:
print(int('123')) # 123
print(int('1010', 2)) # 10 ( binary system)
print(int('FF', 16)) # 255 (hexadecimal)
print(int(3.14)) # 3
16. float(x)
Converts to a floating point number:
print(float('3.14')) # 3.14
print(float('inf')) # inf
print(float(5)) # 5.0
17. bool(x)
Converts it to a boolean value:
print(bool(0)) # False
print(bool(1)) # True
print(bool('')) # False
print(bool('hello')) # True
print(bool([])) # False
print(bool([1, 2])) # True
18. complex(real, imag=0)
Creates a complex number:
print(complex(3, 4)) # (3+4j)
print(complex('3+4j')) # (3+4j)
print(complex(5)) # (5+0j)
Functions for working with collections
19. list(iterable)
Creates a list from an iterable object:
print(list('hello')) # ['h', 'e', 'l', 'l', 'o']
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list((1, 2, 3))) # [1, 2, 3]
20. tuple(iterable)
Creates a tuple from an iterable object:
print(tuple([1, 2, 3])) # (1, 2, 3)
print(tuple('hello')) # ('h', 'e', 'l', 'l', 'o')
21. set(iterable)
Creates multiple (unique elements):
print(set([1, 2, 2, 3, 3])) # {1, 2, 3}
print(set('hello')) # {'h', 'e', 'l', 'o'}
22. frozenset(iterable)
Creates an immutable set:
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})
# fs.add(4) # Error! frozenset is immutable
23. dict(mapping_or_iterable)
Creates a dictionary:
print(dict([('a', 1), ('b', 2)])) # {'a': 1, 'b': 2}
print(dict(a=1, b=2)) # {'a': 1, 'b': 2}
print(dict(zip(['a', 'b'], [1, 2]))) # {'a': 1, 'b': 2}
Functions for working with iterators
24. iter(object, sentinel=None)
Creates an iterator from an object:
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
25. next(iterator, default=None)
Gets the next iterator element:
numbers = iter([1, 2, 3])
print(next(numbers)) # 1
print(next(numbers)) # 2
print(next(numbers)) # 3
print(next(numbers, 'END')) # 'END' (default value)
26. reversed(sequence)
Creates a reverse iterator:
print(list(reversed([1, 2, 3, 4]))) # [4, 3, 2, 1]
print(list(reversed('hello'))) # ['o', 'l', 'l', 'e', 'h']
27. sorted(iterable, key=None, reverse=False)
Returns a sorted list:
print(sorted([3, 1, 4, 1, 5])) # [1, 1, 3, 4, 5]
print(sorted(['banana', 'apple', 'cherry'])) # ['apple', 'banana', 'cherry']
print(sorted([3, 1, 4, 1, 5], reverse=True)) # [5, 4, 3, 1, 1]
print(sorted(['apple', 'banana', 'cherry'], key=len)) # ['apple', 'banana', 'cherry']
Higher-order functions
28. map(function, iterable)
Applies a function to each element:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Converting strings to
str_numbers = ['1', '2', '3', '4']
int_numbers = list(map(int, str_numbers))
print(int_numbers) # [1, 2, 3, 4]
29. filter(function, iterable)
Filters elements by condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
# Filtering non-empty strings
words = ['hello', '', 'world', '', 'python']
non_empty = list(filter(None, words))
print(non_empty) # ['hello', 'world', 'python']
Logical functions
30. all(iterable)
Checks if all the elements are true:
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(all([1, 2, 3])) # True
print(all([1, 0, 3])) # False
print(all([])) # True (empty sequence)
31. any(iterable)
Checks if there is at least one true element:
print(any([False, False, False])) # False
print(any([False, True, False])) # True
print(any([0, 0, 1])) # True
print(any([])) # False (empty sequence)
Functions for working with objects and attributes
32. type(object)
Returns the object type:
print(type(5)) # <class 'int'>
print(type('hello')) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type(lambda x: x)) # <class 'function'>
33. isinstance(object, classinfo)
Checks whether an object is an instance of the class:
print(isinstance(5, int)) # True
print(isinstance('hello', str)) # True
print(isinstance([1, 2], list)) # True
print(isinstance(5, (int, float))) # True (checking multiple types)
34. issubclass(class, classinfo)
Checks whether a class is a subclass.:
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal)) # True
print(issubclass(Animal, Dog)) # False
35. hasattr(object, name)
Checks if an object has an attribute.:
class Person:
def __init__(self):
self.name = "Anna"
person = Person()
print(hasattr(person, 'name')) # True
print(hasattr(person, 'age')) # False
36. getattr(object, name, default=None)
Gets the attribute value of an object:
class Person:
def __init__(self):
self.name = "Anna"
person = Person()
print(getattr(person, 'name')) # 'Anna'
print(getattr(person, 'age', 25)) # 25 (default value)
37. setattr(object, name, value)
Sets the value of an object attribute:
class Person:
pass
person = Person()
setattr(person, 'name', 'Boris')
setattr(person, 'age', 30)
print(person.name ) # 'Boris'
print(person.age) # 30
38. delattr(object, name)
Removes an attribute of an object:
class Person:
def __init__(self):
self.name = "Anna"
self.age = 25
person = Person()
delattr(person, 'age')
print(hasattr(person, 'age')) # False
39. dir(object=None)
Retrieves a list of object attributes:
print(dir(str)) # List of all string methods
print(dir([])) # List of all list methods
# For a custom class
class MyClass:
def __init__(self):
self.attr = 'value'
def method(self):
pass
obj = MyClass()
print(dir(obj)) # Includes 'attr' and 'method'
Functions for working with memory and identification
40. id(object)
Returns the unique identifier of the object:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(id(a)) # Unique identifier
print(id(b)) # Other identifier
print(id(c)) # Same as that of 'a'
print(a is c) # True
print(a is b) # False
41. hash(object)
Returns the hash value of the object:
print(hash('hello')) # Hash strings
print(hash(42)) # Hash numbers
print(hash((1, 2, 3))) # Hash tuples
# Lists are not hashable
# print(hash([1, 2, 3])) # Error!
42. callable(object)
Checks whether the object can be called as a function:
def my_function():
pass
class MyClass:
def __call__(self):
pass
print(callable(my_function)) # True
print(callable(MyClass)) # True
print(callable(MyClass())) # True
print(callable(42)) # False
Functions for working with symbols and encoding
43. ord(c)
Returns the Unicode character code:
print(ord('A')) # 65
print(ord('a')) # 1072
print(ord('€')) # 8364
44. chr(i)
Returns a Unicode character:
print(chr(65)) # 'A'
print(chr(1072)) # 'a'
print(chr(8364)) #'€'
45. ascii(object)
Returns the ASCII representation of the object:
print(ascii('hello')) #"'hello'"
print(ascii('hello')) #"'\u043f\u0440\u0438\u0432\u0435\u0442'"
print(ascii(['a', 'b'])) # "['a', '\u0431']"
Functions for working with numeric systems
46. bin(x)
Converts a number to binary:
print(bin(10)) # '0b1010'
print(bin(255)) # '0b11111111'
print(bin(-5)) # '-0b101'
47. oct(x)
Converts a number to an octal system:
print(oct(8)) # '0o10'
print(oct(64)) # '0o100'
print(oct(255)) # '0o377'
48. hex(x)
Converts a number to hexadecimal:
print(hex(255)) # '0xff'
print(hex(16)) # '0x10'
print(hex(1000)) # '0x3e8'
Functions for working with files
49. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Opens the file for reading or writing:
# Writing to a file
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Hello, world!')
# Reading from a file
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content) # 'Hello, world!'
# Reading lines
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
Functions for working with bytes
50. bytes(source, encoding='utf-8', errors='strict')
Creates an immutable byte array:
print(bytes('hello', 'utf-8')) # b'hello'
print(bytes([65, 66, 67])) # b'ABC'
print(bytes(5)) # b'\x00\x00\x00\x00\x00'
51. bytearray(source, encoding='utf-8', errors='strict')
Creates a mutable byte array:
ba = bytearray('hello', 'utf-8')
print(ba) # bytearray(b'hello')
ba[0] = 72 # Change the first byte to 'H'
print(ba) # bytearray(b'hello')
52. memoryview(object)
Creates a memory representation object:
data = bytearray(b'hello')
mv = memoryview(data)
print(mv[0]) # 104 (character code 'h')
mv[0] = 72 # Change to 'H'
print(data) # bytearray(b'Hello')
Functions for working with code
53. eval(expression, globals=None, locals=None)
Executes a Python expression from the string:
result = eval('2 + 3 * 4')
print(result) # 14
x = 10
result = eval('x * 2 + 5')
print(result) # 25
# Be careful! eval can be dangerous
# Never use with untrusted input
54. exec(object, globals=None, locals=None)
Executes Python code from the string:
code = '''
def greet(name):
return f"Hello, {name}!"
result = greet("Anna")
print(result)
"'
exec(code) # Outputs: Hello, Anna!
55. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compiles the source code into a code object:
code = compile('print("Hello, World!")', 'string', 'exec')
exec(code) # Outputs: Hello, World!
# Compilation of an expression
expr = compile('2 + 3', '<string>', 'eval')
result = eval(expr)
print(result) # 5
Functions for working with global and local variables
56. globals()
Returns a dictionary of global variables:
global_var = "I am global"
def show_globals():
print('global_var' in globals()) # True
print(globals()['global_var']) # "I am global"
show_globals()
57. locals()
Returns a dictionary of local variables:
def my_function():
local_var = "I'm local"
param = 42
print(locals()) # {'local_var': 'I'm local', 'param': 42}
my_function()
Functions for working with classes
58. property(fget=None, fset=None, fdel=None, doc=None)
Creates a class property:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
circle = Circle(5)
print(circle.radius) # 5
print(circle.area) # 78.53975
59. staticmethod(function)
Creates a static method of the class:
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
print(MathUtils.add(5, 3)) # 8
print(MathUtils.multiply(4, 7)) # 28
60. classmethod(function)
Creates a class method:
class Person:
species = "Homo sapiens"
def __init__(self, name):
self.name = name
@classmethod
def get_species(cls):
return cls.species
@classmethod
def create_anonymous(cls):
return cls("Anonymous")
print(Person.get_species()) # "Homo sapiens"
anon = Person.create_anonymous()
print(anon.name ) # "Anonymous"
Functions for working with slices
61. slice(start, stop, step=None)
Creates a slice object:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice creation
s1 = slice(2, 8) # Equivalent to [2:8]
s2 = slice(1, 9, 2) # Equivalent to [1:9:2]
print(my_list[s1]) # [2, 3, 4, 5, 6, 7]
print(my_list[s2]) # [1, 3, 5, 7]
Formatting functions
62. format(value, format_spec='')
Formats the value according to the specification:
print(format(3.14159, '.2f')) # '3.14'
print(format(1234, ',')) # '1,234'
print(format(255, 'x')) # 'ff'
print(format(255, 'b')) # '11111111'
print(format(0.5, '%')) # '50.000000%'
63. repr(object)
Returns the "official" string representation of the object:
print(repr('hello')) # "'hello'"
print(repr([1, 2, 3])) # "[1, 2, 3]"
print(repr({'a': 1})) # "{'a': 1}"
# The difference between str() and repr()
import datetime
now = datetime.datetime.now()
print(str(now)) # Readable
print format(repr(now)) # Technical format
Additional functions
64. object()
Creates a new base object:
obj = object()
print(type(obj)) # <class 'object'>
print(dir(obj)) # Basic object methods
65. help(object=None)
Outputs background information:
help(len) # Help for the len function
help(str) # Help for the str class
help(list.append) # Help with the append method
66. import(name, globals=None, locals=None, fromlist=(), level=0)
Dynamically imports the module:
# Beware! Usually use a regular import
math_module = __import__('math')
print(math_module.sqrt(16)) # 4.0
# It is better to use importlib for dynamic import
importlib
json_module = importlib.import_module('json')
Key points to remember:
- Built-in functions are available without import
- They are optimized for performance
- Many functions are universal and work with different types of data
- Proper use of built-in functions makes the code more readable and pythonic