Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Write a function that returns the length of a sequence

Implement a function that returns the length (number of items) of any iterable or sequence.

Python practice8 minFunctions & ScopeBeginnerLast updated March 17, 2026

Problem statement

Write a function seq_length(seq) that returns the number of items in seq. If seq supports len(seq), use that. If not (for example, a generator), iterate through the iterable and count items. The function should not modify the iterable beyond consuming it when necessary.

Task

Create seq_length(seq) to return how many items are in seq. Support sequences (with len) and general iterables (by iterating).

Examples

List length

Input

seq_length([1, 2, 3])

Output

3

The list has three elements.

Input format

One argument: any sequence or iterable.

Output format

An integer representing the number of items.

Constraints

Do not assume all inputs support len(). If len() raises TypeError, count by iterating.

Samples

Sample 1

Input

seq_length('hello')

Output

5

Strings support len(), returning 5.