This document provides a comprehensive list of all Python built-in functions with their syntax and usage examples.
Returns the absolute value of a number.
abs(-5) # Returns 5
abs(3.14) # Returns 3.14
abs(-2+3j) # Returns 3.605551275463989Returns a tuple containing the quotient and remainder when dividing a by b.
divmod(10, 3) # Returns (3, 1)
divmod(9, 4) # Returns (2, 1)Returns the largest item in an iterable or the largest of two or more arguments.
max(1, 2, 3) # Returns 3
max([1, 2, 3]) # Returns 3
max("abc", key=len) # Returns "abc"Returns the smallest item in an iterable or the smallest of two or more arguments.
min(1, 2, 3) # Returns 1
min([1, 2, 3]) # Returns 1
min("abc", "ab", key=len) # Returns "ab"Returns base raised to the power exp; if mod is present, returns base**exp % mod.
pow(2, 3) # Returns 8
pow(2, 3, 5) # Returns 3 (8 % 5)Returns a floating point number rounded to ndigits precision after the decimal point.
round(3.14159, 2) # Returns 3.14
round(1234.5, -1) # Returns 1230.0Sums start and the items of an iterable from left to right and returns the total.
sum([1, 2, 3]) # Returns 6
sum([1, 2, 3], 10) # Returns 16Returns a Boolean value, i.e. one of True or False.
bool(1) # Returns True
bool(0) # Returns False
bool("hello") # Returns True
bool("") # Returns FalseReturns a new array of bytes.
bytearray(5) # Returns bytearray(b'\x00\x00\x00\x00\x00')
bytearray("hello", "utf-8") # Returns bytearray(b'hello')Returns a new "bytes" object.
bytes(5) # Returns b'\x00\x00\x00\x00\x00'
bytes("hello", "utf-8") # Returns b'hello'Returns a complex number with the value real + imag*1j.
complex(1, 2) # Returns (1+2j)
complex("3+4j") # Returns (3+4j)Creates a new dictionary.
dict() # Returns {}
dict(a=1, b=2) # Returns {'a': 1, 'b': 2}
dict([('a', 1), ('b', 2)]) # Returns {'a': 1, 'b': 2}Returns a floating point number constructed from a number or string.
float(3) # Returns 3.0
float("3.14") # Returns 3.14Returns a new frozenset object.
frozenset([1, 2, 3]) # Returns frozenset({1, 2, 3})
frozenset("hello") # Returns frozenset({'h', 'e', 'l', 'o'})Returns an integer object constructed from a number or string.
int(3.14) # Returns 3
int("42") # Returns 42
int("ff", 16) # Returns 255Returns a list whose items are the same and in the same order as iterable's items.
list("hello") # Returns ['h', 'e', 'l', 'l', 'o']
list(range(3)) # Returns [0, 1, 2]Returns a new set object.
set([1, 2, 3, 2]) # Returns {1, 2, 3}
set("hello") # Returns {'h', 'e', 'l', 'o'}Returns a string version of object.
str(123) # Returns "123"
str([1, 2, 3]) # Returns "[1, 2, 3]"Returns a tuple whose items are the same and in the same order as iterable's items.
tuple([1, 2, 3]) # Returns (1, 2, 3)
tuple("hello") # Returns ('h', 'e', 'l', 'l', 'o')Returns True if all elements of the iterable are true (or if the iterable is empty).
all([True, True, True]) # Returns True
all([True, False, True]) # Returns False
all([]) # Returns TrueReturns True if any element of the iterable is true.
any([False, True, False]) # Returns True
any([False, False]) # Returns False
any([]) # Returns FalseReturns an enumerate object.
list(enumerate(['a', 'b', 'c'])) # Returns [(0, 'a'), (1, 'b'), (2, 'c')]
list(enumerate(['a', 'b'], start=1)) # Returns [(1, 'a'), (2, 'b')]Constructs an iterator from those elements of iterable for which function returns true.
list(filter(lambda x: x > 0, [-1, 0, 1, 2])) # Returns [1, 2]
list(filter(None, [0, 1, False, True])) # Returns [1, True]Returns the length (the number of items) of an object.
len("hello") # Returns 5
len([1, 2, 3]) # Returns 3
len({"a": 1}) # Returns 1Returns an iterator that applies function to every item of iterable.
list(map(str, [1, 2, 3])) # Returns ['1', '2', '3']
list(map(lambda x: x**2, [1, 2, 3])) # Returns [1, 4, 9]Returns an immutable sequence of numbers.
list(range(5)) # Returns [0, 1, 2, 3, 4]
list(range(1, 5)) # Returns [1, 2, 3, 4]
list(range(0, 10, 2)) # Returns [0, 2, 4, 6, 8]Returns a reverse iterator.
list(reversed([1, 2, 3])) # Returns [3, 2, 1]
list(reversed("hello")) # Returns ['o', 'l', 'l', 'e', 'h']Returns a new sorted list from the items in iterable.
sorted([3, 1, 2]) # Returns [1, 2, 3]
sorted([3, 1, 2], reverse=True) # Returns [3, 2, 1]
sorted(["apple", "pie"], key=len) # Returns ["pie", "apple"]Returns an iterator of tuples.
list(zip([1, 2, 3], ['a', 'b', 'c'])) # Returns [(1, 'a'), (2, 'b'), (3, 'c')]
list(zip([1, 2], ['a', 'b'], [10, 20])) # Returns [(1, 'a', 10), (2, 'b', 20)]Reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
name = input("Enter your name: ") # Waits for user inputPrints objects to the text stream file, separated by sep and followed by end.
print("Hello", "World") # Prints: Hello World
print("Hello", "World", sep="-") # Prints: Hello-World
print("Hello", end="") # Prints: Hello (no newline)open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Opens file and returns a corresponding file object.
f = open("file.txt", "r") # Opens file for reading
f = open("file.txt", "w") # Opens file for writing
f = open("file.txt", "a") # Opens file for appendingReturns True if the object argument appears callable, False if not.
callable(print) # Returns True
callable(42) # Returns False
callable(lambda: 1) # Returns TrueReturns a list of valid attributes for that object.
dir(str) # Returns list of string methods
dir() # Returns names in current scopeReturns the value of the named attribute of object.
getattr(list, "append") # Returns <method 'append' of 'list' objects>
getattr(list, "nonexistent", "default") # Returns "default"Returns a dictionary representing the current global symbol table.
globals() # Returns dict of global variablesReturns True if the string is the name of one of the object's attributes.
hasattr(list, "append") # Returns True
hasattr(list, "nonexistent") # Returns FalseReturns the "identity" of an object.
id(42) # Returns unique integer for objectReturns True if the object argument is an instance of the classinfo argument.
isinstance(42, int) # Returns True
isinstance("hello", str) # Returns True
isinstance([1, 2], (list, tuple)) # Returns TrueReturns True if class is a subclass of classinfo.
issubclass(bool, int) # Returns True
issubclass(str, int) # Returns FalseUpdates and returns a dictionary representing the current local symbol table.
def func():
x = 1
return locals() # Returns {'x': 1}Returns the type of an object or creates a new type object.
type(42) # Returns <class 'int'>
type("hello") # Returns <class 'str'>Returns the dict attribute for a module, class, instance, or any other object.
class Example:
def __init__(self):
self.x = 1
obj = Example()
vars(obj) # Returns {'x': 1}Returns an iterator object.
iter([1, 2, 3]) # Returns list iterator
iter("hello") # Returns string iteratorRetrieves the next item from the iterator.
it = iter([1, 2, 3])
next(it) # Returns 1
next(it) # Returns 2
next(it, "end") # Returns 3
next(it, "end") # Returns "end"Deletes the named attribute from object.
class Example:
x = 1
obj = Example()
delattr(obj, 'x') # Removes attribute xSets the named attribute on the given object to the specified value.
class Example:
pass
obj = Example()
setattr(obj, 'x', 42) # Sets obj.x = 42Compiles the source into a code or AST object.
code = compile("print('hello')", "<string>", "exec")
exec(code) # Prints: helloEvaluates the given expression and returns the result.
eval("2 + 3") # Returns 5
eval("len('hello')") # Returns 5Executes the given object (string, bytes, or code object).
exec("print('hello')") # Prints: hello
exec("x = 42") # Creates variable xReturns a string containing a printable representation of an object with non-ASCII characters escaped.
ascii("hello") # Returns "'hello'"
ascii("café") # Returns "'caf\\xe9'"Converts an integer number to a binary string prefixed with "0b".
bin(10) # Returns '0b1010'
bin(-10) # Returns '-0b1010'Converts a value to a "formatted" representation.
format(42, 'b') # Returns '101010' (binary)
format(3.14159, '.2f') # Returns '3.14'Converts an integer number to a lowercase hexadecimal string prefixed with "0x".
hex(255) # Returns '0xff'
hex(16) # Returns '0x10'Converts an integer number to an octal string prefixed with "0o".
oct(8) # Returns '0o10'
oct(64) # Returns '0o100'Returns an integer representing the Unicode character.
ord('A') # Returns 65
ord('€') # Returns 8364Returns the string representing a character whose Unicode code point is the integer i.
chr(65) # Returns 'A'
chr(8364) # Returns '€'Returns a string containing a printable representation of an object.
repr("hello") # Returns "'hello'"
repr([1, 2, 3]) # Returns '[1, 2, 3]'Returns the hash value of the object (if it has one).
hash("hello") # Returns hash value
hash((1, 2, 3)) # Returns hash valueReturns a memory view object created from the given argument.
data = bytearray(b"hello")
mv = memoryview(data) # Returns memory viewReturns a slice object representing the set of indices.
s = slice(2, 8, 2)
[1, 2, 3, 4, 5, 6, 7, 8, 9][s] # Returns [3, 5, 7]Returns a new featureless object.
obj = object() # Creates new objectReturns a property attribute.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radiusReturns a class method for the given function.
class MyClass:
@classmethod
def my_method(cls):
return "class method"Returns a static method for the given function.
class MyClass:
@staticmethod
def my_method():
return "static method"Returns a proxy object that delegates method calls to a parent or sibling class.
class Parent:
def method(self):
return "parent"
class Child(Parent):
def method(self):
return super().method() + " child"Imports a module (advanced use, prefer import statement).
math = __import__('math')
math.sqrt(16) # Returns 4.0This document covers all Python built-in functions as of Python 3.11. For the most up-to-date information, refer to the official Python documentation.