0

Program to sort:

a = [ 7 ,6,4,3,8,1 ]
i = 1
while i < 7:
     if a[i] > a[i+1]:
         l= a[i]
         a[i]=a[i+1]
         a[i+1]=l
     i+=1
print a

i am getting an error list index is out of range, how should i change my code to solve it ?

2 Answers 2

0

Note that the length of the list a is 6, so the indices you can use to access to its elements are 0, 1, 2, 3, 4, 5.

Now, since you are using

a[i + 1]

to access to the list a, the maximum value i can take is 4 (i+1 = 4+1 = 5 -> the maximum index you can use), so your while condition should be:

while i < 5:
    ...

or the equivalent

while i <= 4
0
a = [ 7 ,6,4,3,8,1 ]
i = 1
while i < 5:
   if a[i] > a[i+1]:
     l= a[i]
     a[i]=a[i+1]
     a[i+1]=l
   i+=1
print a

I should be less than 5 here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.