Python Reference
Every Python built-in function, method, statement, exception and the most-used standard library modules in one place. Concise, accurate pages with live examples that run in your browser.
Built-in Functions
-
abs()Returns the absolute value of a number. -
all()Tests whether every item of an iterable is true. -
any()Tests whether any item of an iterable is true. -
ascii()Returns an ASCII-only representation of an object. -
bin()Converts an integer to a binary string. -
bool()Converts a value to a Boolean. -
bytearray()Creates a mutable bytes object. -
bytes()Creates an immutable bytes object. -
callable()Tests whether an object is callable. -
chr()Returns the character for a Unicode code point. -
classmethod()Turns a method into a class method. -
compile()Compiles source into a code object. -
complex()Creates a complex number. -
delattr()Deletes an attribute. -
dict()Creates a dictionary. -
dir()Lists names in a scope or attributes of an object. -
divmod()Returns quotient and remainder together. -
enumerate()Pairs items with an index. -
eval()Evaluates an expression string (and why to avoid it). -
exec()Executes Python code from a string. -
filter()Keeps items for which a function is true. -
float()Converts a value to a float. -
format()Formats a value using a format spec. -
frozenset()Creates an immutable set. -
getattr()Gets an attribute by name. -
globals()Returns the global namespace. -
hasattr()Tests whether an attribute exists. -
hash()Returns the hash of an object. -
help()Starts the built-in help system. -
hex()Converts an integer to a hexadecimal string. -
id()Returns an object's identity. -
input()Reads a line from standard input. -
int()Converts a value to an integer. -
isinstance()Tests an object's type, including subclasses. -
issubclass()Tests a class relationship. -
iter()Returns an iterator. -
len()Returns the number of items. -
list()Creates a list. -
locals()Returns the local namespace. -
map()Applies a function to every item. -
max()Returns the largest item. -
memoryview()Creates a view of binary data. -
min()Returns the smallest item. -
next()Gets the next item of an iterator. -
object()The base class of all classes. -
oct()Converts an integer to an octal string. -
open()Opens a file. -
ord()Returns the code point of a character. -
pow()Raises to a power, optionally modulo. -
print()Prints values to standard output. -
property()Creates a managed attribute. -
range()Creates a sequence of integers. -
repr()Returns the developer representation. -
reversed()Returns a reverse iterator. -
round()Rounds a number. -
set()Creates a set. -
setattr()Sets an attribute by name. -
slice()Creates a slice object. -
sorted()Returns a new sorted list. -
staticmethod()Turns a method into a static method. -
str()Converts a value to a string. -
sum()Adds up the items. -
super()Accesses the parent class. -
tuple()Creates a tuple. -
type()Returns a type or creates a class. -
vars()Returns an object's __dict__. -
zip()Pairs items from several iterables. -
built-in constantsTrue, False, None, Ellipsis and NotImplemented. -
breakpoint()Starts the debugger. -
aiter() and anext()Async iteration built-ins.
String Methods
-
str.capitalize()Capitalizes the first character. -
str.casefold()Returns an aggressively lower-cased string. -
str.center()Centers a string in a field. -
str.count()Counts occurrences of a substring. -
str.encode()Encodes a string to bytes. -
str.endswith()Tests the end of a string. -
str.expandtabs()Replaces tabs with spaces. -
str.find()Returns the lowest index of a substring or -1. -
str.format()Formats a string with replacement fields. -
str.format_map()Formats a string from a mapping. -
str.index()Like find() but raises ValueError. -
str.isalnum()Tests for letters and digits only. -
str.isalpha()Tests for letters only. -
str.isascii()Tests for ASCII characters only. -
str.isdecimal()Tests for decimal digits. -
str.isdigit()Tests for digits. -
str.isidentifier()Tests for a valid identifier. -
str.islower()Tests for lower case. -
str.isnumeric()Tests for numeric characters. -
str.isprintable()Tests for printable characters. -
str.isspace()Tests for whitespace only. -
str.istitle()Tests for title case. -
str.isupper()Tests for upper case. -
str.join()Joins an iterable of strings. -
str.ljust()Left-justifies a string. -
str.lower()Converts to lower case. -
str.lstrip()Strips leading characters. -
str.maketrans() and translate()Character translation tables. -
str.partition()Splits at the first separator. -
str.removeprefix()Removes a prefix. -
str.removesuffix()Removes a suffix. -
str.replace()Replaces substrings. -
str.rfind()Finds the highest index of a substring. -
str.rjust()Right-justifies a string. -
str.rpartition()Splits at the last separator. -
str.rsplit()Splits from the right. -
str.rstrip()Strips trailing characters. -
str.split()Splits into a list. -
str.splitlines()Splits at line boundaries. -
str.startswith()Tests the start of a string. -
str.strip()Strips leading and trailing characters. -
str.swapcase()Swaps upper and lower case. -
str.title()Title-cases words. -
str.upper()Converts to upper case. -
str.zfill()Pads with zeros on the left. -
string formattingf-strings, format spec mini-language and % formatting (concept page). -
string literals and escapesQuotes, escapes, raw and bytes literals (concept page).
Lists, Tuples and Ranges
-
list.append()Adds an item at the end. -
list.clear()Removes all items. -
list.copy()Returns a shallow copy. -
list.count()Counts occurrences of a value. -
list.extend()Appends items from an iterable. -
list.index()Returns the first index of a value. -
list.insert()Inserts an item at an index. -
list.pop()Removes and returns an item. -
list.remove()Removes the first matching value. -
list.reverse()Reverses the list in place. -
list.sort()Sorts the list in place. -
slicingThe slice syntax for sequences. -
list comprehensionsBuilding lists from iterables. -
unpacking and star expressionsUnpacking sequences. -
tuple methods and namedtuplecount(), index() and named tuples. -
the range objectProperties and behavior of range.
Dictionaries and Sets
-
dict.clear()Removes all items. -
dict.copy()Returns a shallow copy. -
dict.fromkeys()Creates a dict from keys. -
dict.get()Gets a value with a default. -
dict.items()Returns a view of key-value pairs. -
dict.keys()Returns a view of keys. -
dict.pop()Removes a key and returns its value. -
dict.popitem()Removes the last inserted pair. -
dict.setdefault()Gets or inserts a default. -
dict.update()Updates from another mapping. -
dict.values()Returns a view of values. -
dict merge operatorsThe | and |= operators for dicts. -
dict and set comprehensionsBuilding dicts and sets (concept page). -
set.add()Adds an element. -
set.clear()Removes all elements. -
set.copy()Returns a shallow copy. -
set.difference()Elements in this set but not others. -
set.difference_update()In-place difference. -
set.discard()Removes an element if present. -
set.intersection()Elements common to all sets. -
set.intersection_update()In-place intersection. -
set.isdisjoint()Tests for no common elements. -
set.issubset()Tests for subset. -
set.issuperset()Tests for superset. -
set.pop()Removes an arbitrary element. -
set.remove()Removes an element or raises KeyError. -
set.symmetric_difference()Elements in exactly one set. -
set.union()Elements in any set. -
set.update()Adds elements from iterables.
Numbers and Binary Data
-
int methodsbit_length(), to_bytes(), from_bytes() and friends. -
float methodsis_integer(), as_integer_ratio(), hex() and friends. -
numeric types and conversionint, float, complex and bool rules (concept page). -
arithmetic operators+, -, *, /, //, %, ** and divmod semantics. -
comparison operators==, !=, <, >, chained comparisons and is. -
logical and bitwise operatorsand, or, not, &, |, ^, ~, <<, >>. -
in and not inMembership tests. -
is and is notIdentity tests. -
the walrus operator :=Assignment expressions. -
operator precedenceThe precedence table (concept page). -
bytes and bytearray methodsdecode(), hex(), fromhex() and friends. -
memoryview in depthZero-copy views of binary data.
Statements and Keywords
-
if, elif, elseConditional statements. -
forThe for loop and iteration. -
whileThe while loop. -
break, continue and loop elseLoop control and the else clause. -
passThe null statement. -
defDefining functions. -
lambdaAnonymous functions. -
returnReturning values. -
yieldGenerators. -
classDefining classes. -
try, except, else, finallyException handling. -
raiseRaising exceptions. -
assertAssertions. -
withContext managers. -
import and fromImporting modules. -
global and nonlocalScope declarations. -
delDeleting names, items and slices. -
async and awaitCoroutines. -
match and caseStructural pattern matching. -
type statementType aliases with the type statement. -
the list of keywordsAll Python keywords. -
scopes and the LEGB ruleName resolution. -
*args, **kwargs and parametersParameter kinds. -
decoratorsFunction and class decorators. -
iterators and generatorsThe iterator protocol. -
context managersThe with protocol.
Classes and Special Methods
-
__init__() and __new__()Object creation. -
__str__() and __repr__()String representations. -
__eq__() and __hash__()Equality and hashing. -
__lt__() and ordering methodsComparison methods. -
__len__() and __getitem__()Container protocol. -
__iter__() and __next__()Iterator protocol. -
__call__()Callable objects. -
__enter__() and __exit__()Context manager protocol. -
__getattr__() and __getattribute__()Attribute access hooks. -
__slots__Restricting attributes. -
__add__() and arithmetic methodsOperator overloading. -
__bool__() and __len__() truthinessTruth value testing. -
__class_getitem__() and genericsGeneric classes. -
inheritance and MROMethod resolution order. -
properties and descriptorsManaged attributes. -
dataclasses overviewClasses for data. -
abstract base classesABCs. -
metaclassesClasses of classes.
Exceptions
-
the exception hierarchyThe built-in exception tree. -
BaseException and ExceptionThe base classes. -
ValueErrorRaised for bad values. -
TypeErrorRaised for wrong types. -
KeyErrorRaised for missing keys. -
IndexErrorRaised for bad indexes. -
AttributeErrorRaised for missing attributes. -
NameError and UnboundLocalErrorRaised for unknown names. -
ZeroDivisionError and ArithmeticErrorArithmetic errors. -
ImportError and ModuleNotFoundErrorImport errors. -
OSError and FileNotFoundErrorOperating system errors. -
StopIteration and StopAsyncIterationIteration end signals. -
RecursionErrorStack depth errors. -
RuntimeError and NotImplementedErrorGeneral runtime errors. -
SyntaxError and IndentationErrorCompile-time errors. -
AssertionErrorFailed assertions. -
KeyboardInterrupt and SystemExitControl exceptions. -
ExceptionGroup and except*Grouping exceptions. -
warningsThe warnings module and warning categories. -
exception chainingraise from and __cause__. -
custom exceptionsDefining your own exceptions.
Files, Paths and Text I/O
-
open() modes and encodingsMode strings, encoding, newline. -
file.read(), readline() and readlines()Reading files. -
file.write() and writelines()Writing files. -
file.seek() and tell()File positions. -
iterating over filesReading line by line. -
io.StringIO and BytesIOIn-memory files. -
pathlibObject-oriented paths. -
osOperating system interfaces. -
os.pathPath manipulation functions. -
shutilHigh-level file operations. -
glob and fnmatchFilename patterns. -
tempfileTemporary files and directories. -
csvReading and writing CSV. -
jsonJSON encoding and decoding. -
pickleObject serialization (and its dangers). -
sqlite3The SQLite database interface. -
configparserINI-style configuration files. -
zipfile and tarfileArchives. -
gzip, bz2 and lzmaCompression. -
sysSystem-specific parameters.
Standard Library: Math, Data and Text
-
mathMathematical functions. -
cmathComplex math. -
randomPseudo-random numbers. -
statisticsStatistical functions. -
decimalDecimal arithmetic. -
fractionsRational numbers. -
secretsSecure random values. -
datetimeDates and times. -
timeTime access and conversion. -
calendarCalendar functions. -
zoneinfoIANA time zones. -
reRegular expressions. -
stringString constants and templates. -
textwrapText wrapping. -
unicodedataUnicode database. -
difflibComparing sequences. -
structPacking binary data. -
hashlibHash functions. -
base64Base64 and friends. -
uuidUUID objects.
Standard Library: Data Structures and Functional Tools
-
collectionsSpecialized container types. -
collections.CounterCounting hashable objects. -
collections.defaultdictDicts with default values. -
collections.dequeDouble-ended queues. -
collections.OrderedDict and ChainMapOrdered and layered dicts. -
collections.namedtupleTuples with named fields. -
itertoolsIterator building blocks. -
itertools combinatoric functionsproduct, permutations, combinations. -
functoolsHigher-order functions. -
functools.cache and lru_cacheMemoization. -
functools.partial and reducePartial application and reduce. -
operatorOperators as functions. -
heapqHeap queue algorithms. -
bisectArray bisection. -
arrayCompact numeric arrays. -
copyShallow and deep copy. -
enumEnumerations. -
dataclassesData classes. -
typingType hints. -
abcAbstract base classes. -
contextlibContext manager utilities. -
weakrefWeak references. -
graphlibTopological sorting. -
pprintPretty printing. -
reprlibAlternate repr().
Standard Library: Concurrency, Network and Tools
-
threadingThread-based parallelism. -
multiprocessingProcess-based parallelism. -
concurrent.futuresExecutors and futures. -
asyncioAsynchronous I/O. -
queueSynchronized queues. -
subprocessRunning subprocesses. -
socketLow-level networking. -
http.server and urllibSimple HTTP tools. -
urllib.parseURL parsing. -
argparseCommand-line parsing. -
loggingThe logging facility. -
unittestUnit testing. -
doctestTests in docstrings. -
timeitMeasuring execution time. -
tracebackStack traces. -
inspectInspecting live objects. -
importlibImport machinery. -
platformPlatform identification. -
gcGarbage collector interface. -
disDisassembling bytecode. -
astAbstract syntax trees. -
venv and pipVirtual environments and installing packages (concept page).
Third-party Libraries
-
NumPyArrays and numerical computing overview. -
pandasDataFrames overview. -
MatplotlibPlotting overview. -
requestsHTTP for humans (read-only). -
Flask and FastAPIWeb frameworks overview (read-only). -
pytestTesting framework (read-only). -
SQLAlchemySQL toolkit and ORM overview. -
scikit-learnMachine learning overview.
Practical Pages
-
Python versionsPython 3.8 to 3.14 features by version (concept page). -
PEP 8 style guideThe style rules in practice (concept page). -
the Python data modelObjects, types and names (concept page). -
truth value testingTruthy and falsy values (concept page). -
mutable and immutable typesMutability rules (concept page). -
shallow and deep copiesCopy semantics (concept page). -
reading tracebacksHow to read error output (concept page). -
performance tipsCommon performance advice (concept page). -
packaging and projectspyproject.toml and project layout (concept page). -
deprecated and removed featuresThings to avoid (concept page).
Nothing matches โโ. Try the site search.