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.
Work through the guided lesson, then test yourself with a challenge.
Open courseBuilt-in functions
ascii()
ascii(value)Returns a printable representation that escapes non-ASCII characters.
Open entrybin()
bin(integer)Returns the binary representation of an integer.
Open entrycallable()
callable(value)Tests whether a value can be called like a function.
Open entrychr() / ord()
chr(code) / ord(char)Convert between a Unicode code point and a one-character string.
Open entrycompile()
compile(source, filename, mode)Compiles source into a code object that can be executed later.
Open entrycomplex()
complex(real, imag)Creates a complex number.
Open entrydir()
dir(object)Lists the names available on an object, useful for exploration.
Open entryeval()
eval(expression)Evaluates an expression from a string. Never use it on untrusted input.
Open entryexec()
exec(source)Runs statements from a string. Never use it on untrusted input.
Open entryformat()
format(value, spec)Formats a value with a format specification.
Open entrygetattr()
getattr(object, name, default)Reads an attribute by name, with an optional fallback.
Open entryglobals() / locals()
globals() / locals()Return the current global and local namespaces as dictionaries.
Open entryhasattr()
hasattr(object, name)Tests whether an attribute exists.
Open entryhash()
hash(value)Returns the hash of a hashable value.
Open entryhex() / oct()
hex(integer) / oct(integer)Formats an integer in hexadecimal or octal.
Open entryid()
id(object)Returns the identity of an object for its lifetime.
Open entryissubclass()
issubclass(Child, Parent)Tests whether a class inherits from another class.
Open entryiter() / next()
iter(iterable) / next(iterator)Creates an iterator and reads its next value.
Open entrymemoryview()
memoryview(bytes)A view over a buffer that avoids copying when slicing binary data.
Open entryobject()
object()The base class of every object. Useful as a unique sentinel.
Open entryprint() options
print(*values, sep=" ", end="\n")Controls the separator and line ending, which is handy for building output.
Open entryproperty() function
property(getter, setter)The function form of the @property decorator.
Open entrysetattr()
setattr(object, name, value)Sets an attribute by name.
Open entryslice()
slice(start, stop, step)Creates a slice object that can be reused for indexing.
Open entryvars()
vars(object)Returns the __dict__ of an object, or the local namespace.
Open entryBytes and binary data
bytearray
bytearray(data)A mutable sequence of bytes.
Open entrybytes
b"data"An immutable sequence of byte values from 0 to 255.
Open entrybytes.decode()
data.decode("utf-8")Decodes bytes into a string.
Open entrybytes.fromhex()
bytes.fromhex(text)Builds bytes from a hexadecimal string.
Open entrybytes.hex()
data.hex()Returns the hexadecimal representation of bytes.
Open entryint.from_bytes()
int.from_bytes(data, "big")Converts bytes into an integer with a chosen byte order.
Open entryClasses and objects
__eq__
def __eq__(self, other):Defines equality. Return NotImplemented for unrelated types so Python can try the other side.
Open entry__init__
def __init__(self, …):The initialiser called after an instance is created. Set attributes here.
Open entry__repr__
def __repr__(self):The developer representation shown in the REPL and debuggers. It should be unambiguous.
Open entry@classmethod
@classmethodReceives the class instead of the instance. Common for alternative constructors.
Open entry@dataclass
@dataclassGenerates __init__, __repr__ and __eq__ from annotated fields. The best default for data holders.
Open entry@property
@propertyExposes a method as a read-only attribute, keeping the API clean while adding logic.
Open entry@staticmethod
@staticmethodA function namespaced in a class that receives neither self nor cls.
Open entryclass
class User:Defines a new type. Methods take self as the first parameter.
Open entryDunder methods
__len__, __iter__, __getitem__Special methods hook into Python syntax such as len(), iteration and indexing.
Open entryInheritance
class Child(Parent):A subclass inherits methods and attributes from its parent.
Open entrysuper()
super().__init__(…)Calls the parent implementation, usually inside a subclass initialiser.
Open entryDictionaries
Dict comprehension
{k: v for k, v in pairs}Builds a dictionary from any iterable of pairs or computation.
Open entrydict merge operator
a | bCreates a new dictionary with the right side winning on duplicate keys.
Open entrydict.get()
data.get(key, default)Reads a key without raising KeyError. Always pass a default for optional data.
Open entrydict.items()
data.items()A view of key-value pairs, ideal for iteration.
Open entrydict.keys() / values()
data.keys()Views of the keys or values. They reflect later changes to the dictionary.
Open entrydict.pop()
data.pop(key, default)Removes a key and returns its value. Without a default, a missing key raises KeyError.
Open entrydict.popitem()
data.popitem()Removes and returns the last inserted pair.
Open entrydict.setdefault()
data.setdefault(key, default)Returns the value, inserting the default when the key is missing.
Open entrydict.update()
data.update(other)Merges another mapping or key-value pairs into the dictionary.
Open entryIterating a dict
for key in data:Iterating yields keys. Iterate items() when you need values too.
Open entryErrors and files
assert
assert condition, "message"A development-time check. Assertions can be stripped with -O, so never use them for validation.
Open entrycsv module
csv.reader / csv.DictWriterReads and writes CSV safely, including quoting and newlines.
Open entryCustom exception
class AppError(Exception): passA named exception lets callers handle your failures precisely.
Open entryelse and finally
try/except/else/finallyelse runs when no exception occurred; finally always runs for cleanup.
Open entryjson module
json.dumps / json.loadsSerialises Python values to JSON and back. Use indent=2 for readable output.
Open entrypathlib.Path
from pathlib import PathAn object-oriented path API that is clearer than string concatenation.
Open entryraise
raise ValueError("message")Raises an exception. Re-raise with a bare raise inside an except block to preserve the traceback.
Open entrytry / except
try: … except ValueError:Handles expected failures. Catch the narrowest exception you can act on.
Open entrywith
with open(path) as file:Opens a file and closes it automatically, even when an exception occurs.
Open entryExceptions
FileNotFoundError
raise FileNotFoundError(path)Raised when a file or directory does not exist.
Open entryIndexError
raise IndexError("…")Raised when a sequence index is out of range.
Open entryKeyError
raise KeyError(key)Raised when a dictionary key is missing.
Open entryTypeError
raise TypeError("…")Raised when an operation receives an unsupported type.
Open entryValueError
raise ValueError("…")Raised when a value has the right type but an invalid value.
Open entryZeroDivisionError
raise ZeroDivisionError("…")Raised when dividing by zero.
Open entryFiles and paths
file.close() / flush()
file.close() / file.flush()Release the file handle, or push buffered data to disk. Prefer with blocks.
Open entryfile.read()
file.read(size)Reads the whole file, or at most size characters.
Open entryfile.readline() / readlines()
file.readline() / file.readlines()Read one line, or every remaining line as a list.
Open entryfile.seek() / tell()
file.seek(position) / file.tell()Move the read cursor and report its current position.
Open entryfile.write() / writelines()
file.write(text)Write a string, or an iterable of strings, to a file.
Open entryPath parts
path.name / stem / suffix / parentRead the final component, extension-less name, suffix and parent directory.
Open entryPath.exists()
path.exists()True when the path exists.
Open entryPath.glob()
path.glob("*.txt")Finds paths matching a pattern.
Open entryPath.is_file() / is_dir()
path.is_file() / path.is_dir()Tests whether the path is a regular file or a directory.
Open entryPath.iterdir()
path.iterdir()Iterates the entries in a directory.
Open entryPath.mkdir()
path.mkdir(parents=True, exist_ok=True)Creates a directory, optionally including parents and ignoring an existing one.
Open entryPath.read_bytes() / write_bytes()
path.read_bytes()Read or write raw bytes.
Open entryPath.read_text() / write_text()
path.read_text(encoding="utf-8")Read or write a whole text file in one call.
Open entryPath.resolve()
path.resolve()Returns the absolute path with symlinks and .. resolved.
Open entryPath.unlink() / rename()
path.unlink() / path.rename(target)Delete a file or move it to a new path.
Open entryPath.with_suffix()
path.with_suffix(".md")Returns a new path with a different extension.
Open entryFunctions
*args / **kwargs
def f(*args, **kwargs):Collects extra positional arguments into a tuple and extra keyword arguments into a dictionary.
Open entrydef
def name(args):Defines a function. The body is indented and return sends a value back.
Open entryDefault argument
def f(x, y=10):Supplies a value when the argument is omitted. Never use a mutable default such as [].
Open entryDocstring
"""Summary."""The first string in a function, class or module. Tools surface it as documentation.
Open entryFunction as value
handler = process; handler()Functions are first-class objects: pass them, store them and return them.
Open entryKeyword-only arguments
def f(*, limit=10):Arguments after a bare star must be passed by keyword, which keeps call sites readable.
Open entrylambda
lambda x: x * 2A small anonymous function. Use it for short keys, not for named logic.
Open entrymap() / filter()
map(fn, iterable)Applies or filters lazily. Comprehensions are usually more readable in Python.
Open entryreturn
return valueSends a value back to the caller. A function without return returns None.
Open entryFunctions and objects
functools and standard library
datetime.date
date(year, month, day)A calendar date without a time.
Open entrydatetime.fromisoformat()
datetime.fromisoformat(text)Parses ISO 8601 dates and times.
Open entrydatetime.replace()
datetime.replace(year=…)Returns a copy with fields replaced, useful for normalising values.
Open entrydatetime.strftime()
date.strftime(format)Formats a date or datetime with strftime codes.
Open entrydatetime.strptime()
datetime.strptime(text, format)Parses a date string with an explicit format.
Open entrydatetime.time
time(hour, minute, second)A time of day without a date.
Open entrydatetime.timedelta
timedelta(days=1)A duration used for date and time arithmetic.
Open entrydatetime.timestamp()
datetime.timestamp()Converts a local datetime to a Unix timestamp.
Open entryfunctools.cache()
cacheA simpler unbounded cache decorator.
Open entryfunctools.lru_cache()
lru_cache(maxsize=None)Caches a function’s results by arguments. Use it for pure, expensive functions.
Open entryfunctools.partial()
partial(function, *args)Pre-fills arguments to create a specialised function.
Open entryfunctools.reduce()
reduce(function, iterable, initial)Folds an iterable into one value. Prefer sum or a loop when clearer.
Open entryfunctools.wraps()
wraps(function)Preserves the wrapped function’s name and docstring in a decorator.
Open entryjson.dump() / load()
json.dump(data, file)Write or read JSON directly from a file object.
Open entryos.getenv()
os.getenv(name, default)Reads an environment variable with an optional default.
Open entryos.path.join()
os.path.join(a, b)Joins path components using the platform separator.
Open entrysys.argv
sys.argvThe command-line arguments, with the script name first.
Open entrysys.path
sys.pathThe list of directories Python searches for imports.
Open entryIterators, modules and the standard library
collections.Counter
Counter(iterable)Counts values and provides most_common().
Open entrycollections.defaultdict
defaultdict(list)A dictionary that creates a default value for missing keys.
Open entrycollections.deque
deque(iterable)A double-ended queue with fast appends and pops on both ends.
Open entrydatetime
datetime.datetime.now()Current time, arithmetic and formatting. Store timestamps in UTC and convert for display.
Open entryenumerate + zip
for i, (a, b) in enumerate(zip(xs, ys)):Combine tools instead of indexing manually.
Open entryfrom … import
from math import ceilImports a name directly into the namespace.
Open entryGenerator expression
(expr for item in iterable)A lazy version of a comprehension. It uses constant memory.
Open entryif __name__ == "__main__"
if __name__ == "__main__":Runs code only when the file is executed directly, not when imported.
Open entryimport
import mathLoads a module. Import the specific names you need to keep dependencies obvious.
Open entryimport as
import datetime as dtRenames a module or name, which is useful for long module paths.
Open entryitertools.chain()
itertools.chain(a, b)Iterates several iterables as one without copying.
Open entryitertools.groupby()
itertools.groupby(iterable, key)Groups consecutive items with the same key. Sort by the key first.
Open entryrandom
random.choice / random.sampleRandom choices for games and sampling. Use secrets for security-sensitive randomness.
Open entryyield
yield valueTurns a function into a generator that produces values lazily.
Open entryitertools
itertools.accumulate()
accumulate(iterable, func)Yields running totals or another running combination.
Open entryitertools.combinations()
combinations(iterable, r)Every unordered selection of r items.
Open entryitertools.count()
count(start, step)An infinite counter. Combine it with zip or islice.
Open entryitertools.cycle()
cycle(iterable)Repeats an iterable forever.
Open entryitertools.dropwhile()
dropwhile(predicate, iterable)Skips values while the predicate holds, then yields the rest.
Open entryitertools.islice()
islice(iterable, stop)Takes a slice of an iterator without materialising it.
Open entryitertools.permutations()
permutations(iterable, r)Every ordered arrangement of r items.
Open entryitertools.product()
product(a, b)The Cartesian product of the inputs.
Open entryitertools.repeat()
repeat(value, times)Repeats a value a fixed number of times.
Open entryitertools.takewhile()
takewhile(predicate, iterable)Yields values until the predicate first fails.
Open entryitertools.tee()
tee(iterable, n)Splits one iterator into several independent iterators.
Open entryLists
List comprehension
[expr for item in iterable if condition]Builds a list from a loop in one readable expression.
Open entryList slicing
items[start:stop:step]Returns a new list from a range. Assignment through a slice can replace several items at once.
Open entrylist.append()
items.append(value)Adds one value to the end.
Open entrylist.clear()
items.clear()Removes every item in place.
Open entrylist.copy()
items.copy()Returns a shallow copy. Use copy.deepcopy for nested structures.
Open entrylist.count()
items.count(value)Counts occurrences of a value.
Open entrylist.extend()
items.extend(values)Adds every item from another iterable.
Open entrylist.index()
items.index(value)Returns the first index of a value, or raises ValueError.
Open entrylist.insert()
items.insert(index, value)Inserts before an index. Indexes past the end append.
Open entrylist.pop()
items.pop(index=-1)Removes and returns an item. The default is the last one.
Open entrylist.remove()
items.remove(value)Removes the first matching value and raises ValueError when absent.
Open entrylist.reverse()
items.reverse()Reverses in place and returns None.
Open entrylist.sort()
items.sort(key=…, reverse=…)Sorts in place. sorted() returns a new list instead.
Open entryNested comprehension
[[…] for row in grid]A comprehension inside another builds grids and matrices.
Open entrySet operations
set.clear() / copy()
items.clear() / items.copy()Remove every value, or create an independent shallow copy.
Open entryset.difference_update()
items.difference_update(other)Removes values found in the other set.
Open entryset.intersection_update()
items.intersection_update(other)Keeps only values also present in the other set.
Open entryset.isdisjoint()
a.isdisjoint(b)True when the sets share no values.
Open entryset.issuperset()
a.issuperset(b)True when a contains every value of b.
Open entryset.pop()
items.pop()Removes and returns an arbitrary value.
Open entryset.symmetric_difference_update()
items.symmetric_difference_update(other)Keeps values that appear in exactly one set.
Open entryset.update()
items.update(other)Adds every value from another iterable in place.
Open entrySets and tuples
frozenset
frozenset(values)An immutable set that can be used as a dictionary key.
Open entrynamedtuple
namedtuple("Point", "x y")A tuple whose fields have names. Use dataclasses for methods and defaults.
Open entryset difference
a - bValues in the first set that are not in the second.
Open entryset intersection
a & bOnly the values present in both sets.
Open entryset symmetric difference
a ^ bValues in exactly one of the sets.
Open entryset union
a | bEvery value from both sets.
Open entryset.add()
items.add(value)Adds one value. Adding an existing value does nothing.
Open entryset.discard() / remove()
items.discard(value)discard ignores a missing value; remove raises KeyError.
Open entryset.issubset()
a.issubset(b)Tests whether every value of a is in b. The <= operator does the same.
Open entryTuple unpacking
a, b = (1, 2)Assigns tuple items to names in one step. Use *rest to collect the remainder.
Open entryString methods
str.encode()
text.encode("utf-8")Encodes a string to bytes using a named encoding.
Open entrystr.expandtabs()
text.expandtabs(size)Replaces tab characters with spaces.
Open entrystr.format_map()
template.format_map(mapping)Formats using a mapping, which is useful for dictionaries of values.
Open entrystr.isalnum()
text.isalnum()True when every character is a letter or digit and the string is not empty.
Open entrystr.isascii()
text.isascii()True when every character is in the ASCII range.
Open entrystr.isdecimal()
text.isdecimal()True for decimal characters that can form base-10 numbers.
Open entrystr.isidentifier()
text.isidentifier()True when the string is a valid Python identifier.
Open entrystr.islower() / isupper()
text.islower()Tests the case of cased characters in the string.
Open entrystr.isnumeric()
text.isnumeric()True for numeric characters, including fractions and other scripts.
Open entrystr.isprintable()
text.isprintable()True when every character can be printed.
Open entrystr.isspace()
text.isspace()True when the string contains only whitespace.
Open entrystr.istitle()
text.istitle()True when each word starts uppercase and the rest is lowercase.
Open entrystr.lstrip() / rstrip()
text.lstrip(chars)Removes characters from only the left or right side.
Open entrystr.partition()
text.partition(separator)Splits around the first separator into before, separator and after.
Open entrystr.removeprefix()
text.removeprefix(prefix)Removes a prefix only when it is present.
Open entrystr.removesuffix()
text.removesuffix(suffix)Removes a suffix only when it is present.
Open entrystr.rfind() / rindex()
text.rfind(term)Find from the right. rindex raises when the substring is missing.
Open entrystr.rpartition()
text.rpartition(separator)Splits around the last separator.
Open entrystr.rsplit()
text.rsplit(sep, maxsplit)Splits from the right, with an optional limit.
Open entrystr.splitlines()
text.splitlines()Splits on line boundaries and drops the terminators.
Open entrystr.swapcase()
text.swapcase()Swaps uppercase and lowercase characters.
Open entrystr.translate()
text.translate(table)Maps characters through a translation table.
Open entryStrings
repr()
repr(value)Returns a developer-facing representation, which is invaluable when debugging strings.
Open entrystr.casefold()
text.casefold()A stronger lower() for case-insensitive comparison across languages.
Open entrystr.center() / ljust() / rjust()
text.center(width)Pads a string to a width. Useful for simple text tables.
Open entrystr.count()
text.count(term)Counts non-overlapping occurrences.
Open entrystr.find() / index()
text.find(term)find returns -1 when missing; index raises ValueError.
Open entrystr.format()
"{name}".format(name=…)Older formatting style. New code should prefer f-strings.
Open entrystr.isdigit() / isalpha()
text.isdigit()Tests whether every character belongs to the category. Empty strings return False.
Open entrystr.join()
separator.join(iterable)Joins an iterable of strings. It is the inverse of split.
Open entrystr.replace()
text.replace(old, new)Replaces every occurrence. Strings are immutable, so it returns a new string.
Open entrystr.split()
text.split(sep=None)Splits into a list. With no argument it splits on any whitespace and drops empties.
Open entrystr.startswith() / endswith()
text.startswith(prefix)Tests the beginning or end. Accepts a tuple of options.
Open entrystr.strip()
text.strip(chars)Removes whitespace, or the given characters, from both ends.
Open entrystr.title() / capitalize()
text.title()Title-cases each word or capitalises only the first character.
Open entrystr.upper() / lower()
text.upper()Changes case. Use casefold() for case-insensitive comparisons.
Open entryString multiplication
"ab" * 3Repeats a string. Pair it with print for simple separators.
Open entryString slicing
text[start:stop:step]Copies a portion of the string. Negative indexes count from the end.
Open entrySyntax and control flow
break and continue
break / continuebreak exits the loop; continue skips to the next iteration.
Open entrydel statement
del nameRemoves a name or an item from a mutable container.
Open entryenumerate()
enumerate(iterable, start=0)Yields index and value pairs, which removes manual counters.
Open entryf-string
f"Hello, {name}"Formats values into a string. Add :.2f for decimals or :>6 for alignment.
Open entryfor
for item in iterable:Iterates the values of any iterable. Prefer it over index loops.
Open entryif / elif / else
if x > 0: … elif … else …Runs the first branch whose condition is true. Conditions are evaluated in order.
Open entrymatch statement
match value: case pattern:Structural pattern matching, available from Python 3.10.
Open entrypass
passA no-op placeholder that keeps a block syntactically valid.
Open entryrange()
range(start, stop, step)Produces integers up to but not including stop. It is lazy and does not build a list.
Open entryType hints
def f(name: str) -> str:Optional annotations read by tools and editors. They are not enforced at runtime.
Open entryVariable
name = "Ada"A name bound to an object. Python is dynamically typed, but clear names and type hints keep code readable.
Open entryWalrus operator
if (n := len(items)) > 2:Assigns and tests in one expression. Use it to avoid computing a value twice.
Open entrywhile
while condition:Repeats while the condition stays true. Make sure something changes inside.
Open entryzip()
zip(a, b)Pairs values from several iterables and stops at the shortest.
Open entryTypes and built-ins
abs()
abs(value)Returns the absolute value.
Open entryany() / all()
any(iterable) / all(iterable)Tests whether any or all values are truthy. Both short-circuit.
Open entrybool
True / FalseTruth values. Empty containers, 0, None and empty strings are falsy.
Open entrydictionary
{"key": "value"}A mutable mapping of hashable keys to values. Lookup is fast and insertion order is preserved.
Open entrydivmod()
divmod(a, b)Returns the quotient and remainder together.
Open entryfloat
3.14Double-precision floating point. Compare money with decimal.Decimal or integer cents.
Open entryint
42Arbitrary-precision integers. Division with / always returns a float.
Open entryint() / float() / str()
int("42")Converts between basic types. Conversion fails with ValueError when the text is invalid.
Open entryisinstance()
isinstance(value, int)Tests a value against a type or a tuple of types. Prefers inheritance over exact type.
Open entrylen()
len(value)The number of items in a container, character count in a string.
Open entrylist
[1, 2, 3]An ordered, mutable sequence. Use it when order and duplicates matter.
Open entrymin() / max()
min(values)Returns the smallest or largest value. Pass key= for custom ordering.
Open entryNone
NoneThe absence of a value. Test it with is, not ==.
Open entrypow()
pow(base, exp, mod)Raises to a power and can apply a modulus efficiently.
Open entryreversed()
reversed(sequence)Yields items in reverse order without copying the sequence.
Open entryround()
round(value, ndigits)Rounds to the nearest value using banker’s rounding on ties.
Open entryset
{1, 2, 3}An unordered collection of unique hashable values, ideal for membership and de-duplication.
Open entrysorted()
sorted(iterable, key=…, reverse=…)Returns a new sorted list. The original is untouched.
Open entrystr
"text"An immutable sequence of Unicode characters.
Open entrysum()
sum(values, start=0)Adds numbers in an iterable.
Open entryTruthiness
if value:Empty containers, zero, None and empty strings are false; most other values are true.
Open entrytuple
(1, 2, 3)An ordered, immutable sequence. Great for fixed records and dictionary keys.
Open entrytype()
type(value)Returns the type object of a value.
Open entryTurn the reference into recall.
Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.