Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Create a list of integers from 1 to nE02. Access elements by positive and negative indexE03. Slice a list to get first and last three itemsE

Problem No 2

Access elements by positive and negative index

Easy

7 minute session

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.

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.

02:09 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.