Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 5

Write a function that returns the length of a sequence

Easy

8 minute session

Summary

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

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

Explanation

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 input 0

seq_length('hello')

Sample output 0

5

Explanation 0

Strings support len(), returning 5.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:08 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.