![]() |
VOOZH | about |
Python is generally slower than C++ or Java, but choosing the right input method helps reduce time and avoid errors. Below, we’ll look at the most common input techniques in Python, when to use them, and their pros and cons.
Let’s consider a problem: Find the sum of N numbers entered by the user.
Example
Input: 5
1 2 3 4 5
Output: 15
We’ll now explore different input methods in Python that can help solve such problems efficiently.
Below are the main ways to take input in Python, Let’s go through them one by one.
This is the simplest and most commonly used method using input() for taking input and print() for displaying output.
Example: This code takes n as the number of inputs, then reads n integers, sums them up and prints the result.
Explanation:
Python’s sys.stdin and sys.stdout are much faster than input() and print().
This method is widely used in competitive programming for speed optimization.
Example: This program reads input using stdin.readline(), computes the sum of numbers and prints it using stdout.write().
Explanation:
Timing comparison (100k lines each):
Clearly, stdin + stdout is much faster.
Sometimes, we need to unpack multiple values directly into separate variables. For example, if input is:
5 7 19 20
We want:
a = 5
b = 7
c = 19
d = 20
Instead of writing parsing code repeatedly, we can create a helper function.
Example: This function reads a line of space-separated integers and unpacks them into variables.
Explanation: get_ints() uses map(int, split()) to convert input into integers. The values are directly assigned to variables in one line.
When you want the entire line of numbers stored in a list, you can use another helper function. For example, input:
1 2 3 4 5 6 7 8
We want:
Arr = [1, 2, 3, 4, 5, 6, 7, 8]
Example: This program reads integers from a single line and stores them in a list.
Explanation: map(int, split()) converts all numbers to integers. Wrapping it in list() gives us a proper list. Now Arr holds all the integers as a list.
Sometimes, instead of numbers, we just need a string input. For example:
GeeksforGeeks is the best platform to practice Coding.
We want:
string = "GeeksforGeeks if the best platform to practice coding."
Example: This function reads a line of text input as a string.
Explanation: sys.stdin.readline() reads the entire line. .strip() removes trailing newlines. The result is stored as a plain string.
When inputs/outputs are very large, even sys.stdin may not be enough. In such cases, we can use a buffered pipe (io.BytesIO) to further speed up I/O. This is more advanced and usually required only for problems with huge input sizes (2MB+ files).
Example: This program uses a buffer to speed up output operations.
Explanation: Output is written into an in-memory buffer instead of directly printing. At program exit, atexit.register writes all data at once. This reduces the overhead of multiple print() calls.