Problem No 5
Write a function that returns the length of a sequence
Easy≈ 8 minute session
Lesson guide
What this Python exercise practices
Write a function that returns the length of a sequence is a beginner practice lesson that focuses on loops, iteration, counters. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Lists or strings
- Basic for loop syntax
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Practice path
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.
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.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.