Skip to content

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.

def get_element_at_circular_index(lst: list, idx: int):
    return lst[idx % len(lst)]

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:

Input
lst=[1, 2, 3], idx=4
Output
2
Input
lst=[10, 20, 30, 40], idx=-1
Output
40
Input
lst=["a", "b", "c"], idx=5
Output
"c"
Input
lst=[7, 8, 9], idx=0
Output
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

def get_element_at_circular_index(lst: list, idx: int):
    return lst[idx % len(lst)]
def get_element_at_circular_index(lst: list, idx: int):
    circular_idx = idx % len(lst)   # always in range [0, len-1]
    return lst[circular_idx]
get_element_at_circular_index = lambda lst, idx: lst[idx % len(lst)]

Key takeaways

01

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.

02

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.

03

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.