Fast Input/Output
How to read and write data as fast as possible in Python — essential when problems have very large inputs or outputs.
Why input() Is Slow
In competitive programming, some problems have very large inputs — hundreds of thousands or even millions of lines. Python's default input() function has noticeable overhead, and slow I/O alone can cause a correct solution to exceed the time limit.
Python's built-in input() does several things behind the scenes on every call: it flushes buffers, handles encoding, and processes the string. For a few hundred lines this is invisible. For 10^6 lines it adds up to seconds.
sys.stdin bypasses most of that overhead and reads raw bytes directly from the input stream.
sys.stdin.readline
The simplest upgrade — drop-in replacement for input():
Put this line at the top of your solution. Now every call to input() uses the faster version transparently. One important difference: sys.stdin.readline keeps the trailing newline \n, so use .strip() when reading strings:
.split() without arguments strips all whitespace including \n, so for integer arrays you don't need .strip() at all.
Reading All Input at Once
Even faster: read the entire input in one system call, then process it:
This gives you a flat list of all whitespace-separated tokens. Access them with an index:
For very large inputs this is the fastest reading method in Python. The entire file is loaded in one I/O operation.
A cleaner pattern using an iterator:
sys.stdout.write
print() also has overhead — it converts arguments, handles separators and endings, and flushes. For large output, use sys.stdout.write instead:
If you have many lines to output, collect them all first and write once:
One write call for the entire output is significantly faster than thousands of print() calls.
sys.setrecursionlimit
Python's default recursion limit is 1000. This was covered in the previous lesson — as a reminder, set it at the top of any solution that uses recursion:
PyPy vs CPython
Many online judges offer PyPy as an alternative to CPython. PyPy is a JIT-compiled Python interpreter that runs 5–10× faster than CPython on typical CP code — often making a slow Python solution fast enough to pass.
If the judge offers PyPy, prefer it for performance-critical problems. All the I/O tricks in this lesson still apply and are still beneficial under PyPy.
The Standard Fast Template
Here is the template most competitive programmers use at the top of every Python solution: