Useful built-in functions
Useful built-in functions
Built-in Functions
Python comes with a set of powerful functions that are always available — no import needed. This lesson covers the ones that are most useful in competitive programming.
enumerate
When iterating over a list, enumerate gives you both the index and the value at the same time:
You can start the index from any number:
CP use — finding the index of the maximum element:
zip
zip pairs up elements from two or more iterables, stopping at the shortest one:
Building a dict from two lists:
Iterating over two arrays in parallel — very common in CP:
Transposing a matrix using zip:
zip with more than two iterables works the same way — elements are grouped by position across all of them.
map
map applies a function to every element of an iterable. It returns a lazy iterator (like a generator), so wrap it in list() if you need a list:
You have seen this pattern constantly throughout the course:
map with a lambda for custom transformations:
In most cases a list comprehension is more readable than map + lambda. Use map when you already have a named function to pass:
filter
filter keeps only the elements for which the function returns True. Also lazy — wrap in list() to get a list:
Again, a list comprehension is usually more readable:
filter is most useful when you already have a named predicate function:
sorted with key=
You have seen .sort() and sorted() before. The real power comes from the key= parameter — a function that extracts a comparison value from each element:
Sorting tuples by a specific element:
Sorting by multiple criteria — return a tuple from key=. Python compares tuples element by element:
This pattern — negating the primary key to simulate descending order — is extremely common in CP.
lambda
A lambda is an anonymous one-line function. You have seen it throughout this lesson as a key= argument. The syntax is:
The main use case is passing short functions inline without defining them separately:
For anything more complex than a single expression, define a regular function with def instead.