Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Clamp a list index to a valid range

Write a small utility that clamps an index to the valid range for a sequence length. Handle edge cases like zero or negative lengths.

Python practice8 minError Handling & Edge CasesBeginnerLast updated March 20, 2026

Problem statement

When accessing list elements by index you often need to ensure the index is within bounds. Implement a function clamp_index(index, length) that returns an integer index guaranteed to be valid for a sequence of the given length. Rules: - If length is greater than 0, return the index clamped to the inclusive range [0, length-1]. - If length is 0 or negative, return 0 (there is no valid positive index, so 0 acts as a safe default). - Treat the index as an integer (assume callers provide integers). Your implementation should be defensive against surprising length values. Return the computed integer index.

Task

Implement clamp_index(index, length) that returns a safe index between 0 and length-1. Be defensive about invalid lengths.

Examples

Index above range

Input

clamp_index(10, 4)

Output

3

The valid indices for length 4 are 0..3. 10 is clamped to 3.

Input format

Two integers: index and length (sequence length).

Output format

An integer: the clamped index.

Constraints

Do not raise for unexpected length values; handle length <= 0 by returning 0. Assume index is an integer.

Samples

Sample 1

Input

clamp_index(-2, 3)

Output

0

Negative indices are clamped to 0.