Reference · 161 entries

Python 3 Reference

The complete Python 3 reference: every built-in function and method with syntax, parameters, return values and easy examples you can run in your browser.

Python 3 Version history

Every page shows the version that introduced a feature or changed it, linked to the Python version history. Examples run on Python 3.14 in your browser; anything that needs a newer version says so.

Built-in Functions

Every function built into Python 3, from abs() to zip(): always available without an import, with syntax, parameters and runnable examples.

NameDescription
abs()Return the absolute value of a number: its distance from zero, so negative numbers become positive.
aiter()Return an asynchronous iterator for an async iterable: the async counterpart of iter(), used with async for and anext().
all()Return True if every item in an iterable is truthy, or if the iterable is empty. Stops at the first falsy item.
anext()Await and return the next item from an asynchronous iterator, or a default value when it is exhausted.
any()Return True if at least one item in an iterable is truthy. Returns False for an empty iterable and stops at the first truthy item.
ascii()Return a printable representation of an object, like repr(), but with every non-ASCII character escaped.
bin()Convert an integer to a binary string prefixed with 0b, such as bin(5) giving '0b101'. Negative numbers get a minus sign.
bool()Convert a value to True or False using Python's truth rules: zero, empty and None are False, everything else is True.
breakpoint()Pause the program and open the debugger at this line. It calls sys.breakpointhook(), which starts pdb by default.
bytearray()Create a mutable sequence of bytes (integers 0–255). Like bytes, but you can change, append and remove bytes in place.
bytes()Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.
callable()Return True if an object can be called like a function: functions, classes, methods and objects with __call__().
chr()Return the one-character string for a Unicode code point, such as chr(65) giving 'A'. The inverse of ord().
classmethod()Turn a method into a class method that receives the class (cls) instead of an instance. Usually written as @classmethod.
compile()Compile source code into a code object that exec() or eval() can run. Mostly used by tools, REPLs and teaching examples.
complex()Create a complex number from a real and an imaginary part, or parse one from a string such as '1+2j'.
delattr()Delete a named attribute from an object. delattr(obj, 'name') does the same as del obj.name when the name is in a variable.
dict()Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.
dir()List the names an object has, such as attributes and methods. With no argument, list the names in the current scope.
divmod()Divide two numbers and return the quotient and the remainder together as a tuple: (a // b, a % b).
enumerate()Loop over an iterable and get each item together with its index, as (index, item) pairs. The start number is configurable.
eval()Evaluate a single Python expression from a string and return its value. Dangerous with untrusted input.
exec()Execute Python statements from a string or code object. Returns None; like eval(), never use it on untrusted input.
filter()Keep only the items of an iterable for which a function returns True. Returns a lazy iterator, not a list.
float()Convert a number or numeric string to a floating-point number. Also understands 'inf', '-inf' and 'nan'.
format()Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.
frozendict()Create an immutable, hashable dictionary (new in Python 3.15). It can be a dict key or set member and can't be changed.
frozenset()Create an immutable set: unique items that can't be added or removed, so it is hashable and can be a dict key.
getattr()Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.
globals()Return the dictionary of the current module's global names: variables, functions, classes and imports.

All 73 built-in functions →

String Methods

Every Python string method, from capitalize() to zfill(), with syntax, parameters and runnable examples. Strings are immutable, so every method returns a new string.

NameDescription
str.capitalize()Return a copy of the string with the first character in upper case and the rest in lower case.
str.casefold()Return a case-folded copy for caseless comparison. Stronger than lower(): it also handles special cases like German ß.
str.center()Return the string centred in a field of the given width, padded on both sides with a fill character (a space by default).
str.count()Return the number of non-overlapping occurrences of a substring, optionally only between start and end positions.
str.encode()Encode the string into bytes using a text encoding such as UTF-8 (the default), for files, networks and hashing.
str.endswith()Return True if the string ends with the given suffix. Pass a tuple to check several suffixes at once.
str.expandtabs()Return a copy where tab characters are replaced by spaces, aligning to tab stops every tabsize columns (8 by default).
str.find()Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.
str.format()Return a formatted string, filling {} placeholders with the arguments. f-strings are usually simpler.
str.format_map()Like format(), but takes the values from a single mapping, which can be a dict or a dict subclass with defaults.
str.index()Return the lowest index of a substring, like find(), but raise ValueError when it is not found.
str.isalnum()Return True if every character is a letter or a digit and the string isn't empty.
str.isalpha()Return True if every character is a letter (in any alphabet) and the string isn't empty. Spaces and digits return False.
str.isascii()Return True if the string is empty or every character is ASCII (code points 0–127).
str.isdecimal()Return True if every character is a decimal digit (0–9 and their equivalents in other scripts). The strictest digit check.
str.isdigit()Return True if every character is a digit, including superscripts like ². Signs, spaces and decimal points return False.
str.isidentifier()Return True if the string is a valid Python identifier: a name you could use for a variable, function or class.
str.islower()Return True if all cased characters are lower case and there is at least one cased character.
str.isnumeric()Return True if every character is numeric, including digits, fractions like ½ and numerals from other scripts.
str.isprintable()Return True if every character is printable, or the string is empty. Newlines and tabs are not printable.
str.isspace()Return True if every character is whitespace (spaces, tabs, newlines) and the string isn't empty.
str.istitle()Return True if the string is title-cased: each word starts with an upper-case letter followed by lower-case letters.
str.isupper()Return True if all cased characters are upper case and there is at least one cased character.
str.join()Join the strings of an iterable into one string, with this string as the separator between them.
str.ljust()Return the string left-justified in a field of the given width, padded on the right with a fill character.
str.lower()Return a copy of the string with all cased characters converted to lower case.
str.lstrip()Return a copy with leading characters removed: whitespace by default, or any of the characters you pass.
str.maketrans()Create a translation table for translate(): map characters to replacements, or to None to delete them.
str.partition()Split the string at the first occurrence of a separator into a 3-tuple: the part before, the separator, and the part after.
str.removeprefix()Return the string without the given prefix if it starts with it; otherwise return it unchanged.

All 47 string methods →

List Methods

Every Python list method, from append() to sort(), with syntax, parameters and examples you can run. Most of them change the list in place and return None.

NameDescription
list.append()Add one item to the end of a list, changing the list in place. Returns None.
list.clear()Remove every item from the list in place, leaving an empty list. Other references see the change too.
list.copy()Return a shallow copy of the list: a new list with the same items. Nested objects are still shared.
list.count()Return how many times a value appears in the list, comparing each item with ==. Returns 0 if it never appears.
list.extend()Add every item from an iterable to the end of the list, in place. Like append() for many items at once.
list.index()Return the position of the first item equal to a value. Raises ValueError if the value isn't in the list.
list.insert()Insert an item at a given position, shifting later items to the right. Index 0 adds to the front.
list.pop()Remove and return the item at a position, the last item by default. Raises IndexError on an empty list.
list.remove()Remove the first item equal to a value. Raises ValueError if the value is not in the list.
list.reverse()Reverse the order of the items in place. Returns None; use reversed() or slicing for a reversed copy.
list.sort()Sort the list in place, optionally by a key function and in reverse. Returns None; sorted() returns a new list.

Dictionary Methods

Every Python dictionary method, from get() to update(), with syntax, parameters and runnable examples for working with keys and values.

NameDescription
dict.clear()Remove every key and value from the dictionary in place, leaving it empty. Other references see the change too.
dict.copy()Return a shallow copy of the dictionary: a new dict with the same keys and values (nested values are shared).
dict.fromkeys()Create a new dictionary with the given keys, all set to the same value (None by default).
dict.get()Return the value for a key, or a default (None unless given) if the key is missing, without raising KeyError.
dict.items()Return a live view of the dictionary's (key, value) pairs, used to loop over keys and values together.
dict.keys()Return a live view of the dictionary's keys. Supports len(), in and set operations such as & and |.
dict.pop()Remove a key and return its value. Returns the default if given and the key is missing; otherwise raises KeyError.
dict.popitem()Remove and return the last inserted (key, value) pair (LIFO order). Raises KeyError if the dict is empty.
dict.setdefault()Return the value for a key; if the key is missing, insert it with a default value first and return that.
dict.update()Add or overwrite keys from another mapping, an iterable of pairs, or keyword arguments, in place.
dict.values()Return a live view of the dictionary's values, for looping or for functions such as sum() and max().

Set Methods

Every Python set method: add and remove elements, and combine sets with union, intersection and difference, with runnable examples.

NameDescription
set.add()Add one element to the set. Adding an element that is already present does nothing.
set.clear()Remove every element from the set in place, leaving an empty set. Other references to the set see the change.
set.copy()Return a shallow copy of the set: a new set with the same elements, which you can change without affecting the original.
set.difference()Return a new set with the elements of this set that are not in the others. The same as a - b.
set.difference_update()Remove from this set every element found in the others, in place. The same as a -= b.
set.discard()Remove an element if it is present; do nothing if it isn't. The no-error version of remove().
set.intersection()Return a new set with the elements common to this set and all others. The same as a & b.
set.intersection_update()Keep only the elements found in this set and all others, in place. The same as a &= b.
set.isdisjoint()Return True if the set has no elements in common with another iterable.
set.issubset()Return True if every element of this set is also in the other. The same as a <= b.
set.issuperset()Return True if this set contains every element of the other. The same as a >= b.
set.pop()Remove and return an arbitrary element of the set. Raises KeyError if the set is empty.
set.remove()Remove an element from the set. Raises KeyError if it isn't present; use discard() to avoid the error.
set.symmetric_difference()Return a new set with elements in either set but not both. The same as a ^ b.
set.symmetric_difference_update()Update the set in place to keep elements in either set but not both. The same as a ^= b.
set.union()Return a new set with all elements from this set and the others. The same as a | b.
set.update()Add all elements from one or more iterables to the set, in place. The same as a |= b.

Tuple Methods

Tuples are immutable, so they have just two methods, count() and index(). Both are explained here with examples.

NameDescription
tuple.count()Return how many times a value appears in the tuple, comparing each item with ==. Returns 0 if it never appears.
tuple.index()Return the position of the first item equal to a value. Raises ValueError if it isn't in the tuple.