Say I am iterating through a list. I want to check if the list's neighbours (i-1 and i 1) contain a certain element. How do I do this without running into "list index out of range" problem? Example:
list = [1, 0, 1, 0, 1, 0]
for i, j in enumerate(list):
elements = 0
for m in range(i-1,i 2):
if list[m] == 1:
elements = 1
print(list[i], elements)
How do I set boundaries for the range function, so that it doesn't go below 0 and above len(list)?
CodePudding user response:
If you want to iterate for all elements in the target list, one solution is to check the value of second for loop:
_list = [1, 0, 1, 0, 1, 0]
elements = 0
for i, j in enumerate(_list):
for m in range(max(i-1, 0), min(i 2, len(_list))):
if _list[m] == 1:
elements = 1
CodePudding user response:
Try slicing list from the top and bottom
list = [1, 0, 1, 0, 1, 0]
elements = 0
# slice list and start from second element and finish at the penultimate element
for i, j in enumerate(list[1:-1], 1):
for m in range(i-1,i 2):
if list[m] == 1:
elements = 1
or since you don't use list items in the outer loop, loop over range
elements = 0
# start from the second index and finish at the penultimate index
for i in range(1, len(list)-1):
for m in range(i-1,i 2):
if list[m] == 1:
elements = 1