Standard Library Modules
Special modules worth to import
Standard Library Modules
Python comes with a large collection of built-in modules — code that is already installed but needs to be explicitly imported before use. This lesson covers the ones that are most relevant to competitive programming.
math
The math module provides mathematical functions and constants.
Constants
math.inf is useful as an initial value when searching for a minimum:
Integer Functions
math.isqrt is preferred over int(math.sqrt(n)) in CP because sqrt can return slightly off results due to floating point — for example int(math.sqrt(25)) could theoretically return 4 on some systems.
GCD and LCM
Logarithms and Powers
Checking Special Values
math.comb and math.perm
Binomial coefficients and permutations — useful in combinatorics problems:
itertools
The itertools module provides building blocks for working with iterators. Most useful for brute-force enumeration problems.
combinations and permutations
Counting without generating:
combinations_with_replacement
Like combinations but allows picking the same element more than once:
product
Generates the Cartesian product — equivalent to nested loops:
This is cleaner than writing deeply nested for loops when the depth is variable.
accumulate
Computes running totals (or any running operation):
chain
Connects multiple iterables into one sequence without copying any data — useful when you want to iterate over several collections as if they were one:
Iterating over multiple arrays in one loop:
Flatten a 2D list — scan all cells in one loop:
Prepend or append extra values to an iterator:
Merge adjacency lists in a graph:
groupby
Groups consecutive identical elements. Note: the input must be sorted first if you want to group all equal elements together:
functools
The functools module provides tools for working with functions.