python
list-comprehension
type-conversion
integers
programming

How do I convert all strings in a list of lists to integers?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting nested string values to integers is a common preprocessing step for CSV imports, API payloads, and machine-learning datasets. The basic syntax is easy, but robust conversion also needs error handling and clear policy for invalid tokens. A good implementation should be readable, predictable, and testable.

Fast Path with Nested List Comprehension

For clean numeric input, nested list comprehension is concise and efficient.

python
1data = [
2    ["10", "20", "30"],
3    ["40", "50", "60"],
4    ["70", "80", "90"],
5]
6
7converted = [[int(cell) for cell in row] for row in data]
8print(converted)

This creates a new nested list and keeps source data unchanged.

Add Whitespace Normalization

Real-world data often includes extra spaces. Strip before conversion.

python
raw = [[" 1", "2 ", " 3 "], ["4", " 5", "6"]]
normalized = [[int(cell.strip()) for cell in row] for row in raw]
print(normalized)

Normalization early prevents inconsistent behavior across files.

Handle Invalid Values with a Helper

If data quality is inconsistent, define explicit fallback behavior instead of scattered try blocks.

python
1def to_int_or_none(value: str):
2    token = value.strip()
3    if token == "":
4        return None
5    try:
6        return int(token)
7    except ValueError:
8        return None
9
10rows = [["1", "2", ""], ["4", "x", "6"]]
11clean = [[to_int_or_none(cell) for cell in row] for row in rows]
12print(clean)

This tolerant strategy is useful in ingestion pipelines where bad rows should be flagged, not crash the process.

Strict Mode for Contracted Inputs

In some systems, invalid tokens should fail immediately. Use strict mode with clear error context.

python
1def convert_strict(rows: list[list[str]]) -> list[list[int]]:
2    out: list[list[int]] = []
3    for r_idx, row in enumerate(rows):
4        new_row: list[int] = []
5        for c_idx, cell in enumerate(row):
6            try:
7                new_row.append(int(cell.strip()))
8            except ValueError as exc:
9                raise ValueError(f"invalid integer at row {r_idx}, col {c_idx}: {cell!r}") from exc
10        out.append(new_row)
11    return out
12
13print(convert_strict([["7", "8"], ["9", "10"]]))

Detailed errors help debugging large imports.

Stream Conversion for Large Inputs

For very large datasets, convert rows as an iterator instead of loading everything first.

python
1from typing import Iterable, Iterator
2
3
4def convert_rows(rows: Iterable[list[str]]) -> Iterator[list[int]]:
5    for row in rows:
6        yield [int(cell.strip()) for cell in row]
7
8source = ([str(i), str(i + 1), str(i + 2)] for i in range(0, 12, 3))
9for row in convert_rows(source):
10    print(row)

Streaming reduces memory pressure and fits file-processing workflows.

Integrate Validation with Conversion

Conversion is a good place to enforce simple schema checks:

  • row width consistency
  • required columns present
  • numeric range constraints

Example post-conversion range check:

python
1def validate_scores(rows: list[list[int]]) -> None:
2    for r_idx, row in enumerate(rows):
3        for value in row:
4            if value < 0 or value > 100:
5                raise ValueError(f"row {r_idx} has out-of-range score {value}")

Catching these issues early prevents subtle downstream bugs.

Optional NumPy Conversion Path

If downstream code uses NumPy arrays, convert after cleaning.

python
1import numpy as np
2
3rows = [["1", "2", "3"], ["4", "5", "6"]]
4clean = [[int(cell) for cell in row] for row in rows]
5arr = np.array(clean, dtype=np.int64)
6print(arr)
7print(arr.shape)

Converting only once avoids repeated parsing costs.

Common Pitfalls

  • Calling int directly on untrimmed tokens with inconsistent whitespace.
  • Mixing strict and tolerant conversion behavior in the same pipeline.
  • Mutating original nested list and losing raw data for debugging.
  • Swallowing conversion errors without row and column context.
  • Loading very large files into memory when streaming would be simpler.

Summary

  • Use nested list comprehension for clean input and fast conversion.
  • Normalize whitespace before integer parsing.
  • Define explicit strict or tolerant error policy.
  • Stream row conversion for large datasets.
  • Add schema and range checks near conversion boundaries.

Course illustration
Course illustration

All Rights Reserved.