Skip to main content

I/O and Common Reading Patterns

This page leans toward quick reference, not systematic coverage. It keeps only the input patterns I look back at most often when writing scripts, solving problems, or processing ad-hoc data.

Reading a single value

n = int(input())
name = input()
ratio = float(input())

Multiple values on one line

x, y, z = map(int, input().split())

If the types differ, you can split first and then convert individually:

name, age, score = input().split()
age = int(age)
score = float(score)

Reading a list of integers on one line

numbers = list(map(int, input().split()))

First value is a count, followed by data

n, *nums = map(int, input().split())

This pattern works well for input where the first value gives the length and the rest is the sequence.

Multi-line input

Fixed number of lines

rows = []

for _ in range(3):
rows.append(list(map(int, input().split())))

Reading a 2D array

matrix = []

for _ in range(n):
matrix.append(list(map(int, input().split())))

Handling EOF

If you don't know how many lines there are and need to read until end of file:

while True:
try:
line = input().strip()
except EOFError:
break

if not line:
continue

print(line)

Reading from a file

with open("input.txt", "r", encoding="utf-8") as f:
for line in f:
values = line.strip().split()
print(values)

Common output patterns

print(x)
print(x, y, z)
print(*numbers)
print(" ".join(map(str, numbers)))

My own selection order

  • Single value: int(input())
  • Multiple values of the same type on one line: map(..., input().split())
  • Want a list: list(map(...))
  • Variable number of lines: try ... except EOFError
  • File input: with open(...)