0

There are two lists of numbers.

list_1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
list_2 = [0, 2, 5, 7, 8]

for i in range(len(list_1)):
    for l in list_2:
        ...

As such, the loop will iterate over all l in list_2 each time

I need to iterate over only the left, center and right elements in each iteration with i.

For i = 0 there will be elements l = [0, 2, 5]
For i = 1 there will be elements l = [2, 5, 7]
For i = 2 there will be elements l = [5, 7, 8]
For i = 3 there will be elements l = [7, 8]
For i = 4 there will be elements l = [8]
For i = 5 there will be elements l = [8]
For i = 6 there will be elements l = [8]
etc
I.Z.
  • 177
  • 1
  • 1
  • 13
  • Does this answer your question? [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator) – Carcigenicate Jun 22 '21 at 13:58
  • It sounds like you don't want nested loops at all, and just want to iterate a sliding window of the second list. You may need to modify their solutions a bit to handle the edge case of the trailing `8`. – Carcigenicate Jun 22 '21 at 13:58

1 Answers1

2

You just need to slice it appropriately:

list_1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
list_2 = [0, 2, 5, 7, 8]
l = len(list_2)

for i, _ in enumerate(list_1):
    for j in lst2[min(i, l-1):i+3]:
        ...

The slicing produces the following:

[0, 2, 5]
[2, 5, 7]
[5, 7, 8]
[7, 8]
[8]
[8]
[8]
[8]
[8]
[8]
[8]
Ma0
  • 15,057
  • 4
  • 35
  • 65