Home > Software design >  list out of range in pyhton adjacent numbers question
list out of range in pyhton adjacent numbers question

Time:10-19

I have a question which is asking to compare 2 numbers in a list, specifically if the adjacent numbers are postive or negatives However I am stuck on the first part of the question. My idea is to compare the first number using its index with the second number so i 1, but inevitably is goes out of range.

I am missing something here, help is appreciated.

my_list=[-1,2,-3,-4,-5,1,2]
for i in range(len(my_list)):
   print (my_list[i])  
   print (my_list[i 1])

CodePudding user response:

Because you want to print (my_list[i 1]) Your list size is 7 -> when i = 6 -> [i 1] = 7 => my_list[7] <- out of range

CodePudding user response:

You can do it like below:

my_list=[-1,2,-3,-4,-5,1,2]
list_len = len(my_list)
for i in range(list_len-1):
    print(f'comparison {i 1}')
    print (my_list[i])  
    print (my_list[i 1])

CodePudding user response:

my_list=[-1,2,-3,-4,-5,1,2]
list_len = len(my_list)
x =  7 # any positive number
for i in range(x):
   if i < list_len:
       print (my_list[i])  
   if i 1 < list_len:
       print (my_list[i 1])
  • Related