This is my code, I receive an error that "list index out of range", I tried to solve this by accounting for the first and last value before the for loop, however I can not figure out how to make the for loop exclude the first and last object, any ideas?
def minmax(List):
mins=[]
maxs=[]
if List[0]>List[1]: maxs.append(List[0])
if List[0]<List[1]: mins.append(List[0])
if List[-1]>List[-2]: maxs.append(List[-1])
if List[0]<List[1]: mins.append(List[-1])
for i in List[1:-1]:
if List[i] < List[i-1] and List[i] < List[i 1]:
mins.append(List[i])
elif List[i] > List[i-1] and i> List[i 1]:
maxs.append(List[i])
return "mins",mins,"maxs",maxs
nums=[5,0,5,0,5]
minmax(nums)
CodePudding user response:
Your mistake lies in the way you access element in your for loop
for i in List[1:-1]:
if List[i] < List[i-1] and List[i] < List[i 1]:
mins.append(List[i])
elif List[i] > List[i-1] and i> List[i 1]:
maxs.append(List[i])
indeed, i
here is an element of List
not the index of this element, therefore, List[i]
doesn't have any sense neither List[i 1]
nor List[i-1]
.
One fix could be using enumerate to track either the current value of the list but also its index :
for n, i in enumerate(List[1:-1]):
if List[n] < List[n-1] and List[n] < List[n 1]:
mins.append(List[n])
elif List[n] > List[n-1] and i> List[n 1]:
maxs.append(List[n])
I strongly encourage you to use a debugger to understand this behavior.