# Extracting the elements from a loop of sets/ lists

I have a list of integers with the zero removed

Delete[Range[512/2, -512/2, -1], 257]


and I want to get the elements before and after a number within the list.

For example, if I want to get 5 elements before and after the number -255 in the list I should get:

{-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}

This makes the list look like, if we visualize it, a loop of numbers that goes on like:

.... 256 ... -256 , 256 ... -256 , 256...-256 ....

How can I do this?.

• It might be Partition? Sep 19, 2018 at 15:37
• I am not sure what Partition will look like but the result should be a list of numbers like {-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}.
– jsid
Sep 19, 2018 at 15:48

ClearAll[f]
f[lst_, elem_, n_] := Module[{pos = Position[lst, elem][[1, 1]]},
lst[[Mod[Range[pos - n, pos + n], Length @ lst, 1]]]]


Examples:

f[lst, -255, 5]


{-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}

f[lst, 251, 7]


{-255, -256, 256, 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244}