Just use slicing (but be careful about negative indices):
inputlist[max(0, index - 2):index + 3]
will get you a window of up to 5 elements around index
; 2 before and 2 after.
The max()
call ensures that the start index is capped to 0
or up.
This'll work with whatever method you used to produce your index. Say you are using a loop, together with enumerate()
to keep track of the index:
def window(inputlist, index):
return inputlist[max(0, index - 2):index + 3]
for index, elem in enumerate(inputlist):
print window(inputlist, index)
or you found your element with list.index()
:
print window(inputlist, inputlist.index('ham'))
Demo:
>>> def window(inputlist, index):
... return inputlist[max(0, index - 2):index + 3]
...
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 1)
['foo', 'bar', 'baz', 'spam']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 2)
['foo', 'bar', 'baz', 'spam', 'ham']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 4)
['baz', 'spam', 'ham', 'eggs']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 5)
['spam', 'ham', 'eggs']