Back to Blog

[Algorithm] Fast I/O Methods in Python

(edited: March 10, 2026)

Faster Ways to Handle Input

In competitive programming or algorithm challenges, using the standard input() can sometimes lead to a TLE (Time Limit Exceeded). Here is how to read data more efficiently using sys.stdin.readline.

Reading Strings

Reading a Single Line

Python
import sys
s = sys.stdin.readline().rstrip()
  • Note
    • sys.stdin.readline() includes a newline character (\n) at the end of the string.
    • Therefore, using .rstrip() or .strip() is essential. Since .rstrip() only removes the trailing newline on the right, it is generally slightly faster than .strip().

Reading into a List

1. Creating a list of characters

Python
import sys
char_list = list(sys.stdin.readline().rstrip())
  • This approach stores each individual character of the input into a list.

2. Creating a list of words

Python
import sys
word_list = sys.stdin.readline().rstrip().split()
  • Assuming the input is space-separated, this stores each word as an element in the list.

Reading Numbers

Multiple Integers in One Line

Python
import sys
a, b = map(int, sys.stdin.readline().split())
  • Good to Know
    • The split() function divides a string based on a delimiter.
    • If you leave the arguments empty, it automatically splits the string based on whitespace (spaces, tabs, newlines).

Comments