Generate slice that contains element
Let the index of the central item be $c$, and the length of the list be $2r+1$. We assume that the indices of the list are $0,\ldots,n-1$.

There are four cases to consider:


If $n &gt; 2r+1$, then the results are undefined (per your post).
If $0 \leq c-r$ and $c+r \leq n-1$, then you just take elements $c-r,\ldots,c+r$.
If $c-r &lt; 0$, then you take elements $0,\ldots,2r$.
If $c+r \geq n$, then you take elements $n-2r-1,\ldots,n-1$.


In the latter two cases, we are guaranteed to be within bounds since $n &gt; 2r+1$.