-1

I'm looking for a way to iterate over a list oblist with objects starting at a given index x. From this index each iteration I would like to get the two neighboring element indices x-1 and x+1. The iteration should not stop when one side reaches the end of the list, but the other side is not exhausted yet and still has elements. A None element should be returned in this case for the exhausted side.

I tried a couple ways with

for element_indexprev, element_indexnext in zip(range(1,len(oblist)), range(-1,len(oblist), - 1)):

but I'm not getting the desired output. Probably also not the best approach.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Sean M.
  • 595
  • 1
  • 4
  • 21
  • 1
    Does this answer your question? https://stackoverflow.com/questions/1277278/is-there-a-zip-like-function-that-pads-to-longest-length-in-python – Pranav Hosangadi Aug 19 '20 at 18:33
  • Please don't edit-in a solution to the question. If you solved your problem you can post it as an answer (and even accept it). It goes against the idea of this site being a Q&A – Tomerikoo Aug 19 '20 at 19:12

2 Answers2

1

You were close with zip() but as you discovered it stops at the end of the smallest list.

You want itertools.zip_longest(), docs here.

It zips to the length of the longest list instead of the shortest. By default it will pad with None but you can change that with the fillvalue arg if desired.

Glenn Mackintosh
  • 2,765
  • 1
  • 10
  • 18
0

You can solve your problem with a simple for bucle y give you and example below

oblist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
start_index = 7

for x in range(len(oblist)):
    x= x+1
    if start_index - x < 0:
        i = None
    else:
        i = oblist[start_index - x]
    if start_index + x > len(oblist) - 1:
        j = None
    else:
        j = oblist[start_index + x]
    if j == None and i == None:
        break
    else:
        print(i , j)

Output
6 8
5 9
4 10
3 11
2 12
1 13
0 14
None 15
None 16