Problem No 2
Access elements by positive and negative index
Easy≈ 7 minute session
Lesson guide
What this Python exercise practices
Access elements by positive and negative index is a beginner practice lesson that focuses on loops, iteration, counters. It is designed to be solved in about 7 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
- 7 minutes
Practice path
Summary
Retrieve an element from a list using positive or negative indexing. Return None when the index is out of range.
Problem statement
Write a function get_element(lst, idx) that returns the element at position idx in lst. Support negative indices (Python-style). If idx is out of range for lst, return None. This practices indexing and bounds checking.
Task
Implement index access that supports both positive and negative indices and safely handles out-of-range access by returning None.
Examples
Positive index
Input
get_element([10, 20, 30], 1)
Output
20
Explanation
Index 1 corresponds to the second element, 20.
Negative index
Input
get_element([10, 20, 30], -1)
Output
30
Explanation
Index -1 returns the last element, 30.
Input format
Two arguments: a list lst and an integer idx passed to get_element(lst, idx).
Output format
The element at position idx, or None if idx is out of range.
Constraints
Do not raise exceptions for out-of-range indices; return None instead.
Samples
Sample input 0
get_element(['a', 'b', 'c'], -2)
Sample output 0
b
Explanation 0
Index -2 returns the second-to-last element.
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.