Staging: this is not the live site, pydocs.org.
Quickref for the Python Standard Library
The most used parts of Python, grouped by purpose. Click any name for its docs and examples.
- abs
- Return the absolute value of the argument.
- divmod
- Return the tuple (x//y, x%y).
- pow
- Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
- round
- Round a number to a given precision in decimal digits.
- sum
- Return the sum of a 'start' value (default: 0) plus an iterable of numbers
- min
- With a single iterable argument, return its smallest item.
- max
- With a single iterable argument, return its biggest item.
- int
- Convert a number or string to an integer, or return 0 if no arguments are given.
- float
- Convert a string or number to a floating-point number, if possible.
- complex
- Create a complex number from a string or numbers.
- bin
- Return the binary representation of an integer.
- oct
- Return the octal representation of an integer.
- hex
- Return the hexadecimal representation of an integer.
- int.from_bytes
- Return the integer represented by the given array of bytes.
- int.to_bytes
- Return an array of bytes representing an integer.
- math.ceil
- Return the ceiling of x as an Integral.
- math.trunc
- Truncates the Real x to the nearest Integral toward 0.
- math.isqrt
- Return the integer part of the square root of the input.
- math.exp
- Return e raised to the power of x.
- math.log
- Return the logarithm of x to the given base.
- math.isclose
- Determine whether two floating-point numbers are close in value.
- math.comb
- Number of ways to choose k items from n items without repetition and without order.
- math.perm
- Number of ways to choose k items from n items without repetition and with order.
- math.prod
- Calculate the product of all the elements in the input iterable.
- math.fsum
- Return an accurate floating-point sum of values in the iterable seq.
- math.pi
- The mathematical constant π = 3.141592…, to available precision.
- math.inf
- A floating-point positive infinity.
- math.nan
- A floating-point “not a number” (NaN) value.
- math.isnan
- Return True if x is a NaN (not a number), and False otherwise.
- math.isinf
- Return True if x is a positive or negative infinity, and False otherwise.
- random.randint
- Return random integer in range [a, b], including both end points.
- random.randrange
- Choose a random item from range(stop) or range(start, stop[, step]).
- random.uniform
- Get a random number in the range [a, b) or [a, b] depending on rounding.
- random.choices
- Return a k sized list of population elements chosen with replacement.
- random.sample
- Chooses k unique random elements from a population sequence.
- statistics.mode
- Return the most common data point from discrete or nominal data.
- bool
- Returns True when the argument is true, False otherwise.
- all
- Return True if bool(x) is True for all values x in the iterable.
- any
- Return True if bool(x) is True for any x in the iterable.
- callable
- Return whether the object is callable (i.e., some kind of function).
- isinstance
- Return whether an object is an instance of a class or of a subclass thereof.
- issubclass
- Return whether 'cls' is derived from another class or is the same class.
- str
- Create a new string object from the given object.
- repr
- Return the canonical string representation of the object.
- ascii
- Return an ASCII-only representation of an object.
- chr
- Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
- ord
- Return the ordinal value of a character.
- format
- Return type(value).__format__(value, format_spec)
- str.format
- Return a formatted version of the string, using substitutions from args and kwargs.
- str.format_map
- Return a formatted version of the string, using substitutions from mapping.
- str.startswith
- Return True if the string starts with the specified prefix, False otherwise.
- str.endswith
- Return True if the string ends with the specified suffix, False otherwise.
- str.isdigit
- Return True if the string is a digit string, False otherwise.
- str.isnumeric
- Return True if the string is a numeric string, False otherwise.
- str.isalpha
- Return True if the string is an alphabetic string, False otherwise.
- str.isalnum
- Return True if the string is an alpha-numeric string, False otherwise.
- str.isspace
- Return True if the string is a whitespace string, False otherwise.
- str.isupper
- Return True if the string is an uppercase string, False otherwise.
- str.islower
- Return True if the string is a lowercase string, False otherwise.
- str.isidentifier
- Return True if the string is a valid Python identifier, False otherwise.
- str.find
- Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
- str.rfind
- Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
- str.index
- Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
- str.count
- Return the number of non-overlapping occurrences of substring sub in string S[start:end].
- str.upper
- Return a copy of the string converted to uppercase.
- str.lower
- Return a copy of the string converted to lowercase.
- str.casefold
- Return a version of the string suitable for caseless comparisons.
- str.title
- Return a version of the string where each word is titlecased.
- str.swapcase
- Convert uppercase characters to lowercase and lowercase characters to uppercase.
- str.replace
- Return a copy with all occurrences of substring old replaced by new.
- str.strip
- Return a copy of the string with leading and trailing whitespace removed.
- str.lstrip
- Return a copy of the string with leading whitespace removed.
- str.rstrip
- Return a copy of the string with trailing whitespace removed.
- str.zfill
- Pad a numeric string with zeros on the left, to fill a field of the given width.
- str.center
- Return a centered string of length width.
- str.ljust
- Return a left-justified string of length width.
- str.rjust
- Return a right-justified string of length width.
- str.expandtabs
- Return a copy where all tab characters are expanded using spaces.
- str.translate
- Replace each character in the string using the given translation table.
- str.maketrans
- Return a translation table usable for str.translate().
- str.split
- Return a list of the substrings in the string, using sep as the separator string.
- str.rsplit
- Return a list of the substrings in the string, using sep as the separator string.
- str.splitlines
- Return a list of the lines in the string, breaking at line boundaries.
- str.partition
- Partition the string into three parts using the given separator.
- str.rpartition
- Partition the string into three parts using the given separator.
- str.join
- Concatenate any number of strings.
- textwrap.dedent
- Remove any common leading whitespace from every line in `text`.
- textwrap.fill
- Fill a single paragraph of text, returning a new string.
- textwrap.wrap
- Wrap a single paragraph of text, returning a list of wrapped lines.
- string.ascii_letters
- The concatenation of the ascii_lowercase and ascii_uppercase constants described below.
- string.punctuation
- String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}…
- re.match
- Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
- re.search
- Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.
- re.fullmatch
- Try to apply the pattern to all of the string, returning a Match object, or None if no match was found.
- re.findall
- Return a list of all non-overlapping matches in the string.
- re.finditer
- Return an iterator over all non-overlapping matches in the string.
- re.sub
- Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replac…
- re.subn
- Return a 2-tuple containing (new_string, number).
- re.split
- Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
- re.escape
- Escape special characters in a string.
- re.compile
- Compile a regular expression pattern, returning a Pattern object.
- re.Match
- The result of re.search(), re.prefixmatch(), and re.fullmatch().
- re.Match.groups
- Return a tuple containing all the subgroups of the match, from 1.
- re.Match.groupdict
- Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
- re.IGNORECASE
- Perform case-insensitive matching; expressions like [A-Z] will also match lowercase letters.
- re.MULTILINE
- When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (imm…
- re.DOTALL
- Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anyth…
- re.VERBOSE
- This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually sep…
- bytes
- Construct an immutable array of bytes from: - an iterable yielding integers in range(256) - a text string encoded using…
- bytearray
- Construct a mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using …
- memoryview
- Create a new memoryview object which references the given object.
- bytes.fromhex
- Create a bytes object from a string of hexadecimal numbers.
- bytes.decode
- Decode the bytes using the codec registered for encoding.
- str.encode
- Encode the string using the codec registered for encoding.
- bytes.hex
- Create a string of hexadecimal numbers from a bytes object.
- base64.b64encode
- Encode the bytes-like object s using Base64 and return a bytes object.
- struct.unpack
- Return a tuple containing values unpacked according to the format string.
- list
- Built-in mutable sequence.
- range
- Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
- list.extend
- Extend list by appending elements from the iterable.
- list.pop
- Remove and return item at index (default last).
- list.sort
- Sort the list in ascending order and return None.
- len
- Return the number of items in a container.
- sorted
- Return a new list containing all items from the iterable in ascending order.
- reversed
- Return a reverse iterator over the values of the given sequence.
- min
- With a single iterable argument, return its smallest item.
- max
- With a single iterable argument, return its biggest item.
- bisect.bisect_left
- Return the index where to insert item x in list a, assuming a is sorted.
- bisect.insort
- Insert item x in list a, and keep it sorted assuming a is sorted.
- tuple
- Built-in immutable sequence.
- dict
- (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(*…
- dict.fromkeys
- Create a new dictionary with keys from iterable and values set to value.
- dict.get
- Return the value for key if key is in the dictionary, else default.
- dict.keys
- Return a set-like object providing a view on the dict's keys.
- dict.values
- Return an object providing a view on the dict's values.
- dict.items
- Return a set-like object providing a view on the dict's items.
- dict.setdefault
- Insert key with a value of default if key is not in the dictionary.
- dict.update
- If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys()…
- dict.pop
- If the key is not found, return the default if given; otherwise, raise a KeyError.
- dict.popitem
- Remove and return a (key, value) pair as a 2-tuple.
- collections.ChainMap
- A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.
- set
- Build an unordered collection of unique elements.
- frozenset
- Build an immutable unordered collection of unique elements.
- set.discard
- Remove an element from a set if it is a member.
- set.remove
- Remove an element from a set; it must be a member.
- set.pop
- Remove and return an arbitrary set element.
- set.update
- Update the set, adding elements from all others.
- collections.deque
- A list-like sequence optimized for data accesses near its endpoints.
- queue.Queue
- Create a queue object with a given maximum size.
- queue.PriorityQueue
- Variant of Queue that retrieves open entries in priority order (lowest first).
- heapq.heappop
- Pop the smallest item off the heap, maintaining the heap invariant.
- heapq.heapify
- Transform list into a heap, in-place, in O(len(heap)) time.
- heapq.merge
- Merge multiple sorted inputs into a single sorted output.
- dataclasses.asdict
- Return the fields of a dataclass instance as a new dictionary mapping field names to field values.
- array.array
- Return a new array whose items are restricted by typecode, and initialized from the optional initializer value, which m…
- iter
- Get an iterator from an object.
- next
- Return the next item from the iterator.
- zip
- The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip().
- range
- Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
- reversed
- Return a reverse iterator over the values of the given sequence.
- sorted
- Return a new list containing all items from the iterable in ascending order.
- len
- Return the number of items in a container.
- map
- Make an iterator that computes the function using arguments from each of the iterables.
- filter
- Return an iterator yielding those items of iterable for which function(item) is true.
- sum
- Return the sum of a 'start' value (default: 0) plus an iterable of numbers
- min
- With a single iterable argument, return its smallest item.
- max
- With a single iterable argument, return its biggest item.
- all
- Return True if bool(x) is True for all values x in the iterable.
- any
- Return True if bool(x) is True for any x in the iterable.
- itertools.count
- Return a count object whose .__next__() method returns consecutive values.
- itertools.islice
- islice(iterable, stop) --> islice object islice(iterable, start, stop[, step]) --> islice object
- itertools.takewhile
- Return successive entries from an iterable as long as the predicate evaluates to true for each entry.
- itertools.chain
- Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then ele…
- itertools.zip_longest
- Return a zip_longest object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterabl…
- itertools.groupby
- make an iterator that returns consecutive keys and groups from the iterable
- itertools.starmap
- Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given se…
- functools.partial
- Create a new function with partial application of the given arguments and keywords.
- functools.reduce
- Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
- functools.cached_property
- Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for th…
- functools.wraps
- Decorator factory to apply update_wrapper() to a wrapper function
- operator.attrgetter
- Return a callable object that fetches the given attribute(s) from its operand.
- contextlib.chdir
- Non thread-safe context manager to change the current working directory.
- collections.abc.Generator
- ABC for generator classes that implement the protocol defined in PEP 342 that extends iterators with the send(), throw(…
- type
- With one argument, return the type of an object.
- isinstance
- Return whether an object is an instance of a class or of a subclass thereof.
- issubclass
- Return whether 'cls' is derived from another class or is the same class.
- callable
- Return whether the object is callable (i.e., some kind of function).
- id
- Return the identity of an object.
- hash
- Return the integer hash value for the given object.
- getattr
- Get a named attribute from an object.
- setattr
- Sets the named attribute on the given object to the specified value.
- hasattr
- Return whether the object has an attribute with the given name.
- delattr
- Deletes the named attribute from the given object.
- dir
- If called without an argument, return the names in the current scope.
- vars
- Without arguments, equivalent to locals().
- object
- The base class of the class hierarchy.
- super
- Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super().meth(arg) This works for …
- abc.ABC
- Helper class that provides a standard way to create an ABC using inheritance.
- enum.Enum
- Create a collection of name/value pairs.
- enum.StrEnum
- Enum where members are also (and must be) strings
- enum.auto
- Instances are replaced with an appropriate value in Enum class suites.
- copy.copy
- Shallow copy operation on arbitrary Python objects.
- typing.Any
- Special type indicating an unconstrained type.
- typing.Self
- Used to spell the type of "self" in classes.
- Exception
- Common base class for all non-exit exceptions.
- ValueError
- Inappropriate argument value (of correct type).
- OSError
- Base class for I/O related errors.
- ExceptionGroup
- Both of these exception types wrap the exceptions in the sequence excs.
- traceback.print_exc
- Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'.
- warnings.warn
- Issue a warning, or maybe ignore it or raise an exception.
- logging.debug
- Log a message with severity 'DEBUG' on the root logger.
- logging.info
- Log a message with severity 'INFO' on the root logger.
- logging.error
- Log a message with severity 'ERROR' on the root logger.
- logging.exception
- Log a message with severity 'ERROR' on the root logger, with exception information.
- logging.Logger
- Instances of the Logger class represent a single logging channel.
- print
- Prints the values to a stream, or to sys.stdout by default.
- input
- Read a string from standard input.
- pprint.pprint
- Pretty-print a Python object to a stream [default is sys.stdout].
- pprint.pformat
- Format a Python object into a pretty-printed representation.
- open
- Open file and return a stream.
- io.StringIO
- Text I/O implementation using an in-memory buffer.
- io.BytesIO
- Buffered I/O implementation using an in-memory bytes buffer.
- pathlib.Path.glob
- Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative…
- os.path.join
- Join two or more pathname components, inserting '/' as needed.
- os.path.isdir
- Return true if the pathname refers to an existing directory.
- shutil.copytree
- Recursively copy a directory tree and return the destination directory.
- shutil.move
- Recursively move a file or directory to another location.
- os.listdir
- Return a list containing the names of the files in the directory.
- os.makedirs
- Super-mkdir; create a leaf directory and all intermediate ones.
- tempfile.mkdtemp
- User-callable function to create and return a unique temporary directory.
- json.dumps
- Serialize ``obj`` to a JSON formatted ``str``.
- json.loads
- Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object.
- json.dump
- Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object).
- json.load
- Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object.
- csv.reader
- Return a reader object that will process lines from the given iterable.
- csv.writer
- Return a writer object that will write user data on the given file object.
- csv.DictReader
- Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are give…
- csv.DictWriter
- Create an object which operates like a regular writer but maps dictionaries onto output rows.
- pickle.dumps
- Return the pickled representation of the object as a bytes object.
- pickle.loads
- Read and return an object from the given pickle data.
- time.time
- Return the current time in seconds since the Epoch.
- time.sleep
- Delay execution for a given number of seconds.
- time.strftime
- Convert a time tuple to a string according to a format specification.
- zoneinfo.ZoneInfo
- A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key.
- asyncio.run
- Execute the coroutine and return the result.
- asyncio.gather
- Return a future aggregating results from the given coroutines/futures.
- asyncio.sleep
- Coroutine that completes after a given time (in seconds).
- asyncio.wait_for
- Wait for the single Future or coroutine to complete, with timeout.
- asyncio.Queue
- A queue, useful for coordinating producer and consumer coroutines.
- subprocess.run
- Run command with arguments and return a CompletedProcess instance.
- sys.argv
- The list of command line arguments passed to a Python script.
- sys.exit
- Exit the interpreter by raising SystemExit(status).
- sys.path
- A list of strings that specifies the search path for modules.
- sys.version_info
- A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial.
- sys.stdin
- File objects used by the interpreter for standard input, output and errors:
- sys.stdout
- File objects used by the interpreter for standard input, output and errors:
- sys.stderr
- File objects used by the interpreter for standard input, output and errors:
- os.environ
- A mapping object where keys and values are strings that represent the process environment.
- os.getenv
- Get an environment variable, return None if it doesn't exist.
- os.getcwd
- Return a unicode string representing the current working directory.
- os.chdir
- Change the current working directory to the specified path.
- os.cpu_count
- Return the number of logical CPUs in the system.
- shutil.which
- Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if ther…