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?
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)?
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
Answered By – Hayoung
Answer Checked By – Gilberto Lyons (AngularFixing Admin)