1

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?

dabadaba
  • 9,064
  • 21
  • 85
  • 155

1 Answers1

0

I'd compute the min/max starting index for the sublists instead of going too far (and filtering) or not going far enough (and missing something!):

idx = l.index(e)
min_start = max(idx - reach + 1, 0)
max_start = min(idx, n - reach)
result = [l[i:i+reach] for i in range(min_start, max_start + 1)]
superb rain
  • 5,300
  • 2
  • 11
  • 25