Let's say I have a list l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
and a given element e = 'b'
and I want to make 3-length sublists off of elements no further than 3
positions away from our element, including the element. We would want to produce the following result for our example:
[['a', 'b', 'c'], ['b', 'c', 'd']]
As you can see it can't go further left because the element's position is smaller than the reach, and it goes as far as the element 'd'
(index 4
) on the right.
This is my native solution:
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
n = len(l)
reach = 3
e = 'b'
idx = l.index(e)
result = []
for i in range(reach):
lb, rb = idx - i, idx - i + reach
if lb >= 0:
result.append(l[lb:rb])
Is there a more elegant way to do it, e.g. with itertools
or zip
?