Reference

Last updated: 2026-09-22

Reference

Alphabetical list of 269 Python items with syntax, parameters, version support, and examples.

#
OperatorsAll Python operators in one page: arithmetic, comparison, assignment, logical, bitwise, me...
__import__()__import__ is the low-level function behind the import statement; prefer the import statem...
A
abs()abs() returns the absolute value of a number; works on int and float, and returns the magn...
all()all() returns True only if every element of the iterable is truthy (or the iterable is emp...
any()any() returns True if at least one element of the iterable is truthy; False for empty iter...
ascii()ascii() is similar to repr(), but escapes non-ASCII characters as \x, \u, or \U sequences.
anext()anext(awaitable) returns the next item of an async iterator; raises StopAsyncIteration whe...
aiter()aiter(async_iterable) returns an async iterator for an async iterable.
anext()anext(async_iterator[, default]) returns the next item from an async iterator.
asas aliases an imported module/name; also used in with and except to bind a name.
assertassert expression[, msg] raises AssertionError when expression is false; disabled with -O.
asyncasync declares an async def function or async with statement.
awaitawait pauses the async function until the awaitable completes.
B
bin()bin() converts an integer to a binary string prefixed with '0b'.
bool()bool() converts a value to boolean; returns False for 0, 0.0, empty strings/containers and...
breakpoint()breakpoint() drops into the debugger (pdb by default); customizable via PYTHONBREAKPOINT o...
bytearray()bytearray() returns a mutable array of bytes; each element is an integer in 0–255.
bytes()bytes() returns an immutable bytes object; constructible from a bytes-like source, a strin...
breakbreak terminates the nearest enclosing loop.
C
callable()callable() returns True if the object appears callable (function, class, or object with __...
chr()chr() returns a one-character string for the given Unicode code point (0–0x10FFFF).
classmethod()@classmethod marks a method whose first argument is the class itself (cls).
compile()compile() compiles source string into a code object that can be executed by exec() / eval(...
complex()complex() builds a complex number as real + imag*j; with no args returns 0j.
copyright()copyright() prints Python's copyright notice (in the interactive interpreter).
credits()credits() prints credits for the Python project.
continuecontinue jumps to the next loop iteration.
classclass defines a new type; supports single and multiple inheritance.
casecase pattern is a branch inside a match statement.
contextmanager-asyncasync with uses an async context manager; __aenter__/__aexit__ are awaited.
D
delattr()delattr(obj, name) deletes attribute name from obj; equivalent to del obj.name.
dict()dict() creates a dict from keyword args, iterable of pairs, or another mapping.
dir()dir() without args lists names in the current scope; with an object, returns its attribute...
divmod()divmod(a, b) returns (a // b, a % b); works for floats too.
dict.clear()dict.clear() removes all items.
dict.copy()dict.copy() returns a shallow copy of the dict.
dict.fromkeys()dict.fromkeys(iterable[, value]) creates a new dict from iterable keys with value (default...
dict.get()dict.get(key[, default]) returns the value for key; returns default if missing (no KeyErro...
dict.items()dict.items() returns a view of (key, value) pairs.
dict.keys()dict.keys() returns a view of keys; supports set operations.
dict.pop()dict.pop(key[, default]) removes and returns the value; returns default if missing.
dict.popitem()dict.popitem() removes and returns an arbitrary (key, value) pair; raises KeyError if empt...
dict.setdefault()dict.setdefault(key[, default]) returns value for key if present, else inserts key:default...
dict.update()dict.update([other]) merges other into the dict; other can be a dict, iterable of pairs, o...
dict.values()dict.values() returns a view of values.
defdef defines a function with optional params and return.
deldel deletes a name, attribute, or container item (releasing the reference).
E
enumerate()enumerate(iterable, start=0) yields (index, item) pairs, useful in for-loops.
eval()eval() evaluates a Python expression string and returns the result. **Security warning**: ...
exec()exec() executes Python code (statements or blocks) from a string; returns None.
exit()exit() / quit() exits the interactive interpreter by raising SystemExit. Should NOT be use...
elifelif ('else if') follows an if and creates additional branches.
elseelse attached to if/elif/for/while/try runs when no branch matched or the loop completed w...
exceptexcept handles a matching exception (or tuple of types); as binds the exception object.
Ellipsis... is the literal for Ellipsis, used for type hints and placeholders.
F
filter()filter(function, iterable) keeps elements where function returns True; returns an iterator...
float()float() converts a string or number to float; with no args returns 0.0.
format()format(value, format_spec='') returns value formatted according to format_spec.
frozenset()frozenset() returns an immutable set; elements must be hashable, and frozenset itself is h...
file.close()file.close() closes the file and releases system resources.
file.detach()file.detach() separates the underlying binary buffer from the text stream.
file.fileno()file.fileno() returns the integer file descriptor used by the OS.
file.flush()file.flush() forces the internal buffer to be written to disk without closing.
file.isatty()file.isatty() returns whether the stream is connected to a tty device.
file.read()file.read(size=-1) reads the file content; omit size to read everything.
file.readable()file.readable() returns whether the file supports reading.
file.readline()file.readline(size=-1) reads one line; returns an empty string at end of file.
file.readlines()file.readlines() returns a list of all lines, keeping the trailing newlines.
file.seek()file.seek(offset, whence=0) moves the file position; whence 0=start, 1=current, 2=end.
file.seekable()file.seekable() returns whether the file supports random access (seek).
file.tell()file.tell() returns the current file position.
file.truncate()file.truncate(size=None) resizes the file to size; defaults to the current position.
file.writable()file.writable() returns whether the file supports writing.
file.write()file.write(s) writes string s to the file; returns the number of characters written.
file.writelines()file.writelines(lines) writes a sequence of strings; no newline is added automatically.
float.as_integer_ratio()float.as_integer_ratio() returns an exact (numerator, denominator) pair.
float.is_integer()float.is_integer() returns whether the float is integral.
float.hex()float.hex() returns a hexadecimal string representation of the float.
float.fromhex()float.fromhex(s) converts a hex string to a float (class method).
float.conjugate()float.conjugate() returns the float itself; kept for the complex-number interface.
forfor iterates over an iterable; an attached else runs only if the loop wasn't broken.
fromfrom module import name imports specific names from a module.
finallyfinally always runs whether an exception occurred or not.
FalseFalse is the sole false instance of the bool type.
G
getattr()getattr(obj, name[, default]) returns obj.name; returns default if missing (else raises At...
globals()globals() returns the current module's global namespace dict.
globalglobal name declares that name refers to the module-level global inside a function.
H
hasattr()hasattr(obj, name) reports whether obj has an attribute called name.
hash()hash() returns the integer hash of a hashable object; a is b implies hash(a) == hash(b).
help()help() opens interactive help; help(obj) prints the docstring and a brief description.
hex()hex() converts an integer to a hex string prefixed with '0x'.
I
id()id() returns the integer identity of an object (typically its memory address). Objects wit...
input()input([prompt]) reads one line from stdin (stripping the newline); optionally prints a pro...
int()int() converts a number or string to int; strings can specify base.
isinstance()isinstance(obj, classinfo) checks whether obj is an instance of classinfo (or subclass); c...
issubclass()issubclass(cls, classinfo) returns True if cls is a subclass of classinfo.
iter()iter(obj) returns an iterator; iter(callable, sentinel) returns an iterator that calls cal...
int.bit_length()int.bit_length() returns the number of bits needed to represent the integer.
int.bit_count()int.bit_count() returns the number of ones in the binary representation (3.10+).
int.to_bytes()int.to_bytes(length, byteorder) converts an int to bytes; byteorder is 'big' or 'little'.
int.from_bytes()int.from_bytes(bytes, byteorder) converts bytes to an int using the given byte order.
int.as_integer_ratio()int.as_integer_ratio() returns the pair (self, 1).
int.conjugate()int.conjugate() returns the integer itself; kept for the complex-number interface.
ifif selects a branch by a boolean condition; pair with elif and else.
importimport loads a module; can be aliased.
L
len()len() returns the number of items. Works on strings, lists, tuples, dicts, sets, and any o...
list()list() creates a mutable list; with no args returns []; with an iterable returns a list of...
locals()locals() returns the current scope's local namespace dict.
license()license() displays the full Python license text in the interactive interpreter (paged).
list.append()list.append(item) appends item to the end; mutates in place, returns None.
list.clear()list.clear() removes all items; equivalent to del lst[:].
list.copy()list.copy() returns a shallow copy; equivalent to lst[:].
list.count()list.count(x) counts occurrences of x.
list.extend()list.extend(iterable) appends items from iterable; equivalent to lst += list(iterable).
list.index()list.index(x[, start[, end]]) returns the first index of x; raises ValueError if missing.
list.insert()list.insert(i, x) inserts x at index i (clamped to start or end).
list.pop()list.pop([i]) removes and returns item at index i (default last); raises IndexError on emp...
list.remove()list.remove(x) removes the first occurrence of x; raises ValueError if missing.
list.reverse()list.reverse() reverses in place; returns None.
list.sort()list.sort(*, key=None, reverse=False) sorts in place; returns None.
lambdalambda creates an anonymous function (single expression).
M
map()map(function, iterable, ...) applies function to each item; returns an iterator.
max()max() returns the largest item of an iterable (or of multiple args); accepts a key functio...
memoryview()memoryview() exposes the buffer interface of a bytes-like object, allowing zero-copy acces...
min()min() works like max() but returns the smallest item.
matchmatch subject matches subject against case patterns.
N
next()next(iterator[, default]) returns the next item; returns default (or raises StopIteration)...
nonlocalnonlocal name refers to the nearest enclosing scope's variable (not global).
NoneNone is the sole instance of NoneType; commonly used to denote 'no value' (distinct from F...
NotImplementedNotImplemented is returned by binary dunder methods to signal 'try the reflected operation...
O
object()object is the base class of every class; object() returns a featureless instance.
oct()oct() converts an integer to an octal string prefixed with '0o'.
open()open() opens a file and returns a file object. Strongly recommended to use a `with` statem...
ord()ord(c) returns the Unicode code point of single character c.
P
pow()pow(base, exp[, mod]) returns base**exp; the 3-arg form does modular exponentiation effici...
print()print() writes objects as strings to stdout (default); sep joins them, end is appended, fi...
property()property(fget, fset, fdel, doc) wraps accessors into an attribute-like object; also availa...
passpass is a no-op used as a placeholder where a statement is syntactically required.
Q
quit()quit() is an alias of exit(); also raises SystemExit.
R
range()range(stop) or range(start, stop[, step]) returns an immutable integer sequence; commonly ...
repr()repr() returns the official string representation; ideally one that could be passed to eva...
reversed()reversed(seq) returns a reverse iterator; works on list, tuple, str, range, etc.
round()round(number[, ndigits]) rounds using banker's rounding; ndigits=None returns an int.
returnreturn returns a value to the caller and exits the function; with no expr, returns None.
raiseraise explicitly raises an exception (with optional type/message, or re-raises the current...
S
set()set() returns a mutable set; with no args returns an empty set; with an iterable returns t...
setattr()setattr(obj, name, value) sets obj.name = value; equivalent to direct attribute assignment...
slice()slice(stop) or slice(start, stop[, step]) returns a slice object used for __getitem__.
sorted()sorted(iterable, *, key=None, reverse=False) returns a new sorted list; original unchanged...
staticmethod()@staticmethod marks a method that receives neither self nor cls.
str()str() converts an object to str; with no args returns ''.
sum()sum(iterable, start=0) sums iterable items plus start. Do NOT use sum to concatenate strin...
super()super() returns a proxy to the parent class; lets you call parent implementations from a s...
str.capitalize()str.capitalize() upper-cases the first letter and lower-cases the rest.
str.casefold()str.casefold() returns a lowercased string optimized for caseless matching (e.g., German ß...
str.center()str.center(width[, fillchar]) centers the string in a field of width, padded with fillchar...
str.count()str.count(sub[, start[, end]]) counts sub in the given range.
str.encode()str.encode(encoding='utf-8', errors='strict') encodes to bytes.
str.endswith()str.endswith(suffix[, start[, end]]) checks whether the string ends with suffix.
str.expandtabs()str.expandtabs(tabsize=8) replaces tabs with spaces, aligning to the next tabsize boundary...
str.find()str.find(sub[, start[, end]]) returns the lowest index where sub is found, or -1 if not fo...
str.format()str.format(*args, **kwargs) substitutes {} placeholders with args or kwargs.
str.index()str.index(sub) is like find(), but raises ValueError when not found.
str.isalnum()str.isalnum() returns True if the string is non-empty and every char is alphanumeric.
str.isalpha()str.isalpha() returns True if every char is alphabetic and the string is non-empty.
str.isascii()str.isascii() returns True if every char is ASCII (U+0000-U+007F) or the string is empty.
str.isdigit()str.isdigit() returns True if every char is a digit character (incl. Unicode) and the stri...
str.islower()str.islower() returns True if there is at least one lowercase letter and no uppercase lett...
str.isspace()str.isspace() returns True if non-empty and every char is whitespace.
str.istitle()str.istitle() returns True if the string is titlecased.
str.isupper()str.isupper() returns True if there is at least one uppercase letter and no lowercase lett...
str.join()str.join(iterable) joins strings from iterable using str as separator.
str.ljust()str.ljust(width[, fillchar]) left-justifies in a field of width, padded with fillchar.
str.lower()str.lower() returns a lowercased copy.
str.lstrip()str.lstrip([chars]) removes leading chars (default: whitespace).
str.partition()str.partition(sep) returns (before, sep, after); if not found, returns (string, '', '').
str.replace()str.replace(old, new[, count]) replaces old with new up to count times.
str.rfind()str.rfind(sub) returns the highest index where sub is found; -1 if not found.
str.rindex()str.rindex(sub) is like rfind() but raises ValueError when not found.
str.rjust()str.rjust(width[, fillchar]) right-justifies in a field of width, padded with fillchar.
str.rsplit()str.rsplit(sep=None, maxsplit=-1) splits from the right up to maxsplit times.
str.rstrip()str.rstrip([chars]) removes trailing chars (default: whitespace).
str.split()str.split(sep=None, maxsplit=-1) splits the string on sep and returns a list.
str.splitlines()str.splitlines(keepends=False) splits on line boundaries.
str.startswith()str.startswith(prefix[, start[, end]]) checks if the string starts with prefix.
str.strip()str.strip([chars]) removes leading and trailing chars (default: whitespace).
str.swapcase()str.swapcase() swaps the case of every letter.
str.title()str.title() returns a titlecased version: first letter of each word uppercased, rest lower...
str.upper()str.upper() returns an uppercased copy.
str.format_map()str.format_map(mapping) formats using a mapping object instead of kwargs.
str.isdecimal()str.isdecimal() returns True if non-empty and every char is a decimal digit (Unicode categ...
str.isidentifier()str.isidentifier() returns True if the string is a valid Python identifier.
str.isnumeric()str.isnumeric() returns True if non-empty and every char is a Unicode number (incl. CJK).
str.isprintable()str.isprintable() returns True if non-empty and every char is printable.
str.maketrans()str.maketrans(x[, y[, z]]) returns a translation table for str.translate().
str.removeprefix()str.removeprefix(prefix) removes the prefix if present; returns the original otherwise (Py...
str.removesuffix()str.removesuffix(suffix) removes the suffix if present (Python 3.9+).
str.rpartition()str.rpartition(sep) splits at the last occurrence of sep into (before, sep, after).
str.translate()str.translate(table) translates chars using table (typically built with str.maketrans).
str.zfill()str.zfill(width) pads on the left with zeros to total width; preserves sign.
set.add()set.add(elem) adds elem to the set; no-op if already present. Mutates in place.
set.clear()set.clear() removes all elements.
set.copy()set.copy() returns a shallow copy.
set.difference()set.difference(*others) returns elements in set but not in any of others.
set.discard()set.discard(elem) removes elem if present; no error if missing.
set.intersection()set.intersection(*others) returns common elements.
set.isdisjoint()set.isdisjoint(other) returns True if sets have no common elements.
set.issubset()set.issubset(other) returns True if every element of set is in other.
set.issuperset()set.issuperset(other) returns True if set contains every element of other.
set.pop()set.pop() removes and returns an arbitrary element; raises KeyError if empty.
set.remove()set.remove(elem) removes elem; raises KeyError if missing.
set.symmetric_difference()set.symmetric_difference(other) returns elements in either set but not in both.
set.union()set.union(*others) returns the union of set and all others.
set.update()set.update(*others) updates set with the union of itself and others; returns None.
set.intersection_update()set.intersection_update(*others) keeps only elements also found in all others.
set.difference_update()set.difference_update(*others) removes elements found in any of others.
set.symmetric_difference_update()set.symmetric_difference_update(other) updates set with the symmetric difference.
T
tuple()tuple() returns an immutable sequence; with no args returns () or an iterable's items as a...
type()type(obj) returns the object's type; type(name, bases, dict) dynamically creates a new cla...
tuple.count()tuple.count(x) returns the number of times x appears in the tuple.
tuple.index()tuple.index(x[, start[, end]]) returns the first index of x; raises ValueError if missing.
trytry wraps code that may raise; except handles, finally cleans up.
TrueTrue is the sole true instance of the bool type.
V
vars()vars() without args is like locals(); with an object returns object.__dict__.
W
whilewhile repeats the body while the condition is true.
withwith calls __enter__ / __exit__ on a context manager; common for files, locks, connections...
Y
yieldyield turns a function into a generator that pauses at each yield until the next call.
Z
zip()zip(*iterables) combines iterables in parallel, stopping at the shortest (or raising if st...
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏