Python
Programming
List Comparison
Code Optimization
Algorithms

Better way to check if all lists in a list are the same length?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Checking whether every inner list has the same length is a basic structural validation step for matrix-like input, CSV-style records, and preprocessing code. The check is simple, but it still benefits from a clear policy for empty input, good error reporting, and a solution that matches the size and shape of your data. In Python, the cleanest answer is usually a short all(...) check, but there are a few patterns worth knowing.

The Clear Baseline with all

The most readable approach is to compare every row length against the first row.

python
1def same_length(rows):
2    if not rows:
3        return True
4
5    expected = len(rows[0])
6    return all(len(row) == expected for row in rows)
7
8
9print(same_length([[1, 2], [3, 4], [5, 6]]))
10print(same_length([[1], [2, 3]]))

Why this is a good default:

  • It is explicit about the reference length.
  • It short-circuits on the first mismatch.
  • It is easy to extend with diagnostics later.

For most production code, this is the best balance between readability and performance.

Set-Based Check for Concise Scripts

If you only need a Boolean and do not care about short-circuiting, you can collect all unique lengths.

python
1def same_length_set(rows):
2    return len({len(row) for row in rows}) <= 1
3
4
5print(same_length_set([[1, 2], [3, 4], [5, 6]]))
6print(same_length_set([[1], [2, 3]]))

This is compact, but it evaluates every row before returning. That is fine for small collections, but it is less helpful if mismatches are common and you want early exit.

Define Empty-Input Behavior

An empty outer list has no mismatching rows, so many implementations return True. That is mathematically reasonable, but some business rules require at least one row.

If non-empty input is required, separate that rule from the equal-length rule.

python
1def validate_rows(rows):
2    if not rows:
3        raise ValueError("rows must not be empty")
4
5    expected = len(rows[0])
6    return all(len(row) == expected for row in rows)

Keeping those rules separate avoids ambiguous behavior later.

Returning Diagnostics Instead of Only a Boolean

A Boolean is often not enough when you are validating input from users or external systems. Returning the failing index makes the error actionable.

python
1def validate_same_length(rows):
2    if not rows:
3        return True, None
4
5    expected = len(rows[0])
6
7    for index, row in enumerate(rows):
8        if len(row) != expected:
9            return False, {
10                "row_index": index,
11                "actual_length": len(row),
12                "expected_length": expected,
13            }
14
15    return True, None
16
17
18ok, info = validate_same_length([[1, 2], [3], [4, 5]])
19print(ok, info)

This is often the right pattern for APIs, ETL jobs, and validation layers.

When Rows Are Not Actually Lists

The problem statement often says “lists,” but real data may contain tuples, arrays, or generators. Anything without a valid len(...) will break a length-based check.

If your input may be heterogeneous, define the contract first or normalize data up front.

python
def normalized_lengths(rows):
    normalized = [list(row) for row in rows]
    return all(len(row) == len(normalized[0]) for row in normalized) if normalized else True

That conversion costs memory, so it is only appropriate if normalization is already part of your pipeline.

Matrix and Numerical Workflows

If the goal is to feed the data into NumPy or a model, unequal row lengths should usually be rejected before conversion.

python
1import numpy as np
2
3rows = [[1, 2], [3, 4], [5, 6]]
4
5if same_length(rows):
6    arr = np.array(rows)
7    print(arr.shape)
8else:
9    raise ValueError("ragged rows")

Failing early is better than discovering ragged input deep inside numeric code.

Performance Notes

For large inputs:

  • 'all(...) is usually preferable because it short-circuits.'
  • Set-based approaches touch every row.
  • Diagnostics loops are best when you need the first failure detail.

In most applications, readability matters more than micro-optimizing this check. Only benchmark if row validation is in a hot path.

Common Pitfalls

  • Forgetting to define whether empty input should be accepted. Fix by making empty-input policy explicit.
  • Using a one-liner when diagnostic detail is actually needed. Fix by returning failure metadata instead of only a Boolean.
  • Assuming every inner element supports len(...). Fix by validating or normalizing input types before checking lengths.
  • Detecting ragged input only after expensive downstream processing. Fix by validating shape early in the pipeline.
  • Choosing a compact set-based check in workloads where early exit would be more efficient. Fix by using the all(...) pattern when mismatches may appear early.

Summary

  • The clearest Python pattern is comparing every row length to the first row with all(...).
  • Set-based length checks are concise but do not short-circuit.
  • Empty-input behavior should be a deliberate policy choice.
  • Validation helpers should return diagnostics when failures must be actionable.
  • Checking shape early prevents harder-to-debug failures in later processing stages.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms