Quick reference

Python reference

Syntax, built-ins, collections and standard-library patterns with lab-ready examples.

Python favours readability: indentation defines blocks, names are explicit and batteries are included. Reach for the standard library before adding a dependency, and prefer comprehensions over manual loops when the intent stays clear.

Read the full explanationPython Foundations

Work through the guided lesson, then test yourself with a challenge.

Open course
243 entries

Built-in functions

ascii()

ascii(value)

Returns a printable representation that escapes non-ASCII characters.

Open entry

bin()

bin(integer)

Returns the binary representation of an integer.

Open entry

callable()

callable(value)

Tests whether a value can be called like a function.

Open entry

chr() / ord()

chr(code) / ord(char)

Convert between a Unicode code point and a one-character string.

Open entry

compile()

compile(source, filename, mode)

Compiles source into a code object that can be executed later.

Open entry

complex()

complex(real, imag)

Creates a complex number.

Open entry

dir()

dir(object)

Lists the names available on an object, useful for exploration.

Open entry

eval()

eval(expression)

Evaluates an expression from a string. Never use it on untrusted input.

Open entry

exec()

exec(source)

Runs statements from a string. Never use it on untrusted input.

Open entry

format()

format(value, spec)

Formats a value with a format specification.

Open entry

getattr()

getattr(object, name, default)

Reads an attribute by name, with an optional fallback.

Open entry

globals() / locals()

globals() / locals()

Return the current global and local namespaces as dictionaries.

Open entry

hasattr()

hasattr(object, name)

Tests whether an attribute exists.

Open entry

hash()

hash(value)

Returns the hash of a hashable value.

Open entry

hex() / oct()

hex(integer) / oct(integer)

Formats an integer in hexadecimal or octal.

Open entry

id()

id(object)

Returns the identity of an object for its lifetime.

Open entry

issubclass()

issubclass(Child, Parent)

Tests whether a class inherits from another class.

Open entry

iter() / next()

iter(iterable) / next(iterator)

Creates an iterator and reads its next value.

Open entry

memoryview()

memoryview(bytes)

A view over a buffer that avoids copying when slicing binary data.

Open entry

object()

object()

The base class of every object. Useful as a unique sentinel.

Open entry

print() options

print(*values, sep=" ", end="\n")

Controls the separator and line ending, which is handy for building output.

Open entry

property() function

property(getter, setter)

The function form of the @property decorator.

Open entry

setattr()

setattr(object, name, value)

Sets an attribute by name.

Open entry

slice()

slice(start, stop, step)

Creates a slice object that can be reused for indexing.

Open entry

vars()

vars(object)

Returns the __dict__ of an object, or the local namespace.

Open entry

Bytes and binary data

Classes and objects

Dictionaries

Errors and files

Exceptions

Files and paths

file.close() / flush()

file.close() / file.flush()

Release the file handle, or push buffered data to disk. Prefer with blocks.

Open entry

file.read()

file.read(size)

Reads the whole file, or at most size characters.

Open entry

file.readline() / readlines()

file.readline() / file.readlines()

Read one line, or every remaining line as a list.

Open entry

file.seek() / tell()

file.seek(position) / file.tell()

Move the read cursor and report its current position.

Open entry

file.write() / writelines()

file.write(text)

Write a string, or an iterable of strings, to a file.

Open entry

Path parts

path.name / stem / suffix / parent

Read the final component, extension-less name, suffix and parent directory.

Open entry

Path.exists()

path.exists()

True when the path exists.

Open entry

Path.glob()

path.glob("*.txt")

Finds paths matching a pattern.

Open entry

Path.is_file() / is_dir()

path.is_file() / path.is_dir()

Tests whether the path is a regular file or a directory.

Open entry

Path.iterdir()

path.iterdir()

Iterates the entries in a directory.

Open entry

Path.mkdir()

path.mkdir(parents=True, exist_ok=True)

Creates a directory, optionally including parents and ignoring an existing one.

Open entry

Path.read_bytes() / write_bytes()

path.read_bytes()

Read or write raw bytes.

Open entry

Path.read_text() / write_text()

path.read_text(encoding="utf-8")

Read or write a whole text file in one call.

Open entry

Path.resolve()

path.resolve()

Returns the absolute path with symlinks and .. resolved.

Open entry

Path.unlink() / rename()

path.unlink() / path.rename(target)

Delete a file or move it to a new path.

Open entry

Path.with_suffix()

path.with_suffix(".md")

Returns a new path with a different extension.

Open entry

Functions

Functions and objects

functools and standard library

datetime.date

date(year, month, day)

A calendar date without a time.

Open entry

datetime.fromisoformat()

datetime.fromisoformat(text)

Parses ISO 8601 dates and times.

Open entry

datetime.replace()

datetime.replace(year=…)

Returns a copy with fields replaced, useful for normalising values.

Open entry

datetime.strftime()

date.strftime(format)

Formats a date or datetime with strftime codes.

Open entry

datetime.strptime()

datetime.strptime(text, format)

Parses a date string with an explicit format.

Open entry

datetime.time

time(hour, minute, second)

A time of day without a date.

Open entry

datetime.timedelta

timedelta(days=1)

A duration used for date and time arithmetic.

Open entry

datetime.timestamp()

datetime.timestamp()

Converts a local datetime to a Unix timestamp.

Open entry

functools.cache()

cache

A simpler unbounded cache decorator.

Open entry

functools.lru_cache()

lru_cache(maxsize=None)

Caches a function’s results by arguments. Use it for pure, expensive functions.

Open entry

functools.partial()

partial(function, *args)

Pre-fills arguments to create a specialised function.

Open entry

functools.reduce()

reduce(function, iterable, initial)

Folds an iterable into one value. Prefer sum or a loop when clearer.

Open entry

functools.wraps()

wraps(function)

Preserves the wrapped function’s name and docstring in a decorator.

Open entry

json.dump() / load()

json.dump(data, file)

Write or read JSON directly from a file object.

Open entry

os.getenv()

os.getenv(name, default)

Reads an environment variable with an optional default.

Open entry

os.path.join()

os.path.join(a, b)

Joins path components using the platform separator.

Open entry

sys.argv

sys.argv

The command-line arguments, with the script name first.

Open entry

sys.path

sys.path

The list of directories Python searches for imports.

Open entry

Iterators, modules and the standard library

collections.Counter

Counter(iterable)

Counts values and provides most_common().

Open entry

collections.defaultdict

defaultdict(list)

A dictionary that creates a default value for missing keys.

Open entry

collections.deque

deque(iterable)

A double-ended queue with fast appends and pops on both ends.

Open entry

datetime

datetime.datetime.now()

Current time, arithmetic and formatting. Store timestamps in UTC and convert for display.

Open entry

enumerate + zip

for i, (a, b) in enumerate(zip(xs, ys)):

Combine tools instead of indexing manually.

Open entry

from … import

from math import ceil

Imports a name directly into the namespace.

Open entry

Generator expression

(expr for item in iterable)

A lazy version of a comprehension. It uses constant memory.

Open entry

if __name__ == "__main__"

if __name__ == "__main__":

Runs code only when the file is executed directly, not when imported.

Open entry

import

import math

Loads a module. Import the specific names you need to keep dependencies obvious.

Open entry

import as

import datetime as dt

Renames a module or name, which is useful for long module paths.

Open entry

itertools.chain()

itertools.chain(a, b)

Iterates several iterables as one without copying.

Open entry

itertools.groupby()

itertools.groupby(iterable, key)

Groups consecutive items with the same key. Sort by the key first.

Open entry

random

random.choice / random.sample

Random choices for games and sampling. Use secrets for security-sensitive randomness.

Open entry

yield

yield value

Turns a function into a generator that produces values lazily.

Open entry

itertools

Lists

Set operations

Sets and tuples

String methods

str.encode()

text.encode("utf-8")

Encodes a string to bytes using a named encoding.

Open entry

str.expandtabs()

text.expandtabs(size)

Replaces tab characters with spaces.

Open entry

str.format_map()

template.format_map(mapping)

Formats using a mapping, which is useful for dictionaries of values.

Open entry

str.isalnum()

text.isalnum()

True when every character is a letter or digit and the string is not empty.

Open entry

str.isascii()

text.isascii()

True when every character is in the ASCII range.

Open entry

str.isdecimal()

text.isdecimal()

True for decimal characters that can form base-10 numbers.

Open entry

str.isidentifier()

text.isidentifier()

True when the string is a valid Python identifier.

Open entry

str.islower() / isupper()

text.islower()

Tests the case of cased characters in the string.

Open entry

str.isnumeric()

text.isnumeric()

True for numeric characters, including fractions and other scripts.

Open entry

str.isprintable()

text.isprintable()

True when every character can be printed.

Open entry

str.isspace()

text.isspace()

True when the string contains only whitespace.

Open entry

str.istitle()

text.istitle()

True when each word starts uppercase and the rest is lowercase.

Open entry

str.lstrip() / rstrip()

text.lstrip(chars)

Removes characters from only the left or right side.

Open entry

str.partition()

text.partition(separator)

Splits around the first separator into before, separator and after.

Open entry

str.removeprefix()

text.removeprefix(prefix)

Removes a prefix only when it is present.

Open entry

str.removesuffix()

text.removesuffix(suffix)

Removes a suffix only when it is present.

Open entry

str.rfind() / rindex()

text.rfind(term)

Find from the right. rindex raises when the substring is missing.

Open entry

str.rpartition()

text.rpartition(separator)

Splits around the last separator.

Open entry

str.rsplit()

text.rsplit(sep, maxsplit)

Splits from the right, with an optional limit.

Open entry

str.splitlines()

text.splitlines()

Splits on line boundaries and drops the terminators.

Open entry

str.swapcase()

text.swapcase()

Swaps uppercase and lowercase characters.

Open entry

str.translate()

text.translate(table)

Maps characters through a translation table.

Open entry

Strings

repr()

repr(value)

Returns a developer-facing representation, which is invaluable when debugging strings.

Open entry

str.casefold()

text.casefold()

A stronger lower() for case-insensitive comparison across languages.

Open entry

str.center() / ljust() / rjust()

text.center(width)

Pads a string to a width. Useful for simple text tables.

Open entry

str.count()

text.count(term)

Counts non-overlapping occurrences.

Open entry

str.find() / index()

text.find(term)

find returns -1 when missing; index raises ValueError.

Open entry

str.format()

"{name}".format(name=…)

Older formatting style. New code should prefer f-strings.

Open entry

str.isdigit() / isalpha()

text.isdigit()

Tests whether every character belongs to the category. Empty strings return False.

Open entry

str.join()

separator.join(iterable)

Joins an iterable of strings. It is the inverse of split.

Open entry

str.replace()

text.replace(old, new)

Replaces every occurrence. Strings are immutable, so it returns a new string.

Open entry

str.split()

text.split(sep=None)

Splits into a list. With no argument it splits on any whitespace and drops empties.

Open entry

str.startswith() / endswith()

text.startswith(prefix)

Tests the beginning or end. Accepts a tuple of options.

Open entry

str.strip()

text.strip(chars)

Removes whitespace, or the given characters, from both ends.

Open entry

str.title() / capitalize()

text.title()

Title-cases each word or capitalises only the first character.

Open entry

str.upper() / lower()

text.upper()

Changes case. Use casefold() for case-insensitive comparisons.

Open entry

String multiplication

"ab" * 3

Repeats a string. Pair it with print for simple separators.

Open entry

String slicing

text[start:stop:step]

Copies a portion of the string. Negative indexes count from the end.

Open entry

Syntax and control flow

break and continue

break / continue

break exits the loop; continue skips to the next iteration.

Open entry

del statement

del name

Removes a name or an item from a mutable container.

Open entry

enumerate()

enumerate(iterable, start=0)

Yields index and value pairs, which removes manual counters.

Open entry

f-string

f"Hello, {name}"

Formats values into a string. Add :.2f for decimals or :>6 for alignment.

Open entry

for

for item in iterable:

Iterates the values of any iterable. Prefer it over index loops.

Open entry

if / elif / else

if x > 0: … elif … else …

Runs the first branch whose condition is true. Conditions are evaluated in order.

Open entry

match statement

match value: case pattern:

Structural pattern matching, available from Python 3.10.

Open entry

pass

pass

A no-op placeholder that keeps a block syntactically valid.

Open entry

range()

range(start, stop, step)

Produces integers up to but not including stop. It is lazy and does not build a list.

Open entry

Type hints

def f(name: str) -> str:

Optional annotations read by tools and editors. They are not enforced at runtime.

Open entry

Variable

name = "Ada"

A name bound to an object. Python is dynamically typed, but clear names and type hints keep code readable.

Open entry

Walrus operator

if (n := len(items)) > 2:

Assigns and tests in one expression. Use it to avoid computing a value twice.

Open entry

while

while condition:

Repeats while the condition stays true. Make sure something changes inside.

Open entry

zip()

zip(a, b)

Pairs values from several iterables and stops at the shortest.

Open entry

Types and built-ins

abs()

abs(value)

Returns the absolute value.

Open entry

any() / all()

any(iterable) / all(iterable)

Tests whether any or all values are truthy. Both short-circuit.

Open entry

bool

True / False

Truth values. Empty containers, 0, None and empty strings are falsy.

Open entry

dictionary

{"key": "value"}

A mutable mapping of hashable keys to values. Lookup is fast and insertion order is preserved.

Open entry

divmod()

divmod(a, b)

Returns the quotient and remainder together.

Open entry

float

3.14

Double-precision floating point. Compare money with decimal.Decimal or integer cents.

Open entry

int

42

Arbitrary-precision integers. Division with / always returns a float.

Open entry

int() / float() / str()

int("42")

Converts between basic types. Conversion fails with ValueError when the text is invalid.

Open entry

isinstance()

isinstance(value, int)

Tests a value against a type or a tuple of types. Prefers inheritance over exact type.

Open entry

len()

len(value)

The number of items in a container, character count in a string.

Open entry

list

[1, 2, 3]

An ordered, mutable sequence. Use it when order and duplicates matter.

Open entry

min() / max()

min(values)

Returns the smallest or largest value. Pass key= for custom ordering.

Open entry

None

None

The absence of a value. Test it with is, not ==.

Open entry

pow()

pow(base, exp, mod)

Raises to a power and can apply a modulus efficiently.

Open entry

reversed()

reversed(sequence)

Yields items in reverse order without copying the sequence.

Open entry

round()

round(value, ndigits)

Rounds to the nearest value using banker’s rounding on ties.

Open entry

set

{1, 2, 3}

An unordered collection of unique hashable values, ideal for membership and de-duplication.

Open entry

sorted()

sorted(iterable, key=…, reverse=…)

Returns a new sorted list. The original is untouched.

Open entry

str

"text"

An immutable sequence of Unicode characters.

Open entry

sum()

sum(values, start=0)

Adds numbers in an iterable.

Open entry

Truthiness

if value:

Empty containers, zero, None and empty strings are false; most other values are true.

Open entry

tuple

(1, 2, 3)

An ordered, immutable sequence. Great for fixed records and dictionary keys.

Open entry

type()

type(value)

Returns the type object of a value.

Open entry
Keep going

Turn the reference into recall.

Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.