Python cap slice negative bound at list ends

Viewed 36

I want to print a part of the list cut out of its middle

def region_around(lst, index):
    return lst[index-3:index+3]

lst = [i for i in range(10)]
print(region_around(lst, 5)) # correctly prints [2, 3, 4, 5, 6, 7]

print(region_around(lst, 0)) # incorrectly prints []

In the second case, region_around(lst, 0), I want [0, 1, 2] as if the slice had been made with only the positive part lst[:3]

How can I constrain a slice like I want?

1 Answers

I remembered the terminology was "clamp" and looking it up showed me that of course I can just do

def region_around(lst, index):
    return lst[max(0, index-3):index+3]
Related