This is a broader case of the classic question of how to select every n
-th element in a list ( my_list[::n]
)
Suppose I have a list l = range(20)
and for each batch of n
elements, I need to select the i
-th to the k
-th
For example if for every n=10
elements I need to select the 3rd to the 5th, the result is l2 = [2, 3, 4, 12, 13, 14]
What is a pythonic / elegant way to achieve the same result as a plain loop as shown below?
l = range(20)
n = 10
i = 2 # 2 being the index of the 3rd element
k = 4 # 4 being the index of the 5th element
l2 = []
for i, x in enumerate(l):
_i = i % n
if _i >= i and _i <= k:
l2.append(x)
which results in the desired l2