S1Q1 · Get Element at Circular Index¶
⚡ Quick Reference
Function: get_element_at_circular_index(lst: list, idx: int)
Core idea: idx % len(lst) wraps any index - positive or negative - into a valid position.
Key rules:
- idx % len(lst) handles both overflow and negative indices
- Python's % always returns a non-negative result when divisor is positive
- No bounds checking needed - modulo does it all
Problem Statement¶
Problem
Write a function get_element_at_circular_index(lst, idx) that returns the element at index idx using circular (wrap-around) indexing.
Examples:
lst=[1, 2, 3], idx=4
2
lst=[10, 20, 30, 40], idx=-1
40
lst=["a", "b", "c"], idx=5
"c"
lst=[7, 8, 9], idx=0
7
Understanding circular indexing¶
Think of the list as a circle - after the last element, it wraps back to the first:
List: [1, 2, 3] (length 3)
idx=0 → 0%3=0 → 1
idx=1 → 1%3=1 → 2
idx=2 → 2%3=2 → 3
idx=3 → 3%3=0 → 1 (wraps!)
idx=4 → 4%3=1 → 2 ✓
idx=5 → 5%3=2 → 3
idx=-1 → -1%3=2 → 3 (Python % always non-negative)
idx=-4 → -4%3=2 → 3
Python's % always returns non-negative
In Python, -1 % 3 = 2 (not -1 as in some other languages). This means idx % len(lst) handles negative indices correctly without any special case - a single expression covers all situations.
Tracing all examples¶
lst |
idx |
len(lst) |
idx % len |
Element |
|---|---|---|---|---|
[1,2,3] |
4 | 3 | 4%3 = 1 | 2 ✓ |
[10,20,30,40] |
-1 | 4 | -1%4 = 3 | 40 ✓ |
["a","b","c"] |
5 | 3 | 5%3 = 2 | "c" ✓ |
[7,8,9] |
0 | 3 | 0%3 = 0 | 7 ✓ |
Solution approaches¶
Key takeaways¶
idx % len(lst) - one expression for all cases
Modulo maps any integer index - however large or negative - into the valid range [0, len-1]. No if statements, no bounds checking needed.
Python % is always non-negative (for positive divisor)
Unlike C or Java, Python's % always returns a result with the same sign as the divisor. So -1 % 4 == 3, which is exactly the circular index for the last element.
This is already how Python's negative indexing works
Python's built-in lst[-1] uses the same modulo logic internally. The difference here is that idx % len also handles indices beyond the list length, which Python's normal indexing does not.