tetukowski
tetukowski

Reputation: 111

slicing python list beyond its length

I have to slice a Python list/numpy array from an index to -dx and +dx. where dx is constant. for example: (the position/index that contains 1 only for illustration, as the center index).

A = [0, 0, 0, 0, 1, 0, 0, 0, 0]
dx=3
print(A[4-dx: 4+dx+1])  # 4 is the position of '1'

>>>[0, 0, 0, 1, 0, 0, 0]  

But for this case,

B = [0, 1, 0, 0, 0 ,0, 0 ,0, 0]
print(B[1-dx: 1+dx+1])
>>>[]  # because 1-dx <0. 

but what i need from case B is [0, 1, 0, 0, 0]

so i did something like this, to prevent empty list/array, say n is the center index:

if n-dx <0:
    result= B[:n+dx+1]

Although the above method works fine. The original code is quite complicated, and I have to put this if...#complicated version# everywhere.

Is there any other way around? Maybe I miss something.

Thank you!

Upvotes: 1

Views: 737

Answers (1)

Barmar
Barmar

Reputation: 782130

You can use the max() function to bound the index at 0.

print(A[max(0,4-dx): 4+dx+1]) 

Upvotes: 1

Related Questions