I have a code:
l = [5, 8, 1, 3, 2]
still_swapping = True
while still_swapping:
still_swapping = False
for i in range(len(l)):
print(l[i], i)
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
still_swapping = True
print(l)
And, I've the output:
if l[i] > l[i+1]:
IndexError: list index out of range
I don't understand why it's out of range. Can you help me guys, please?
IndexError: list index out of range
is thrown when you try to access an element with such an index that is not in the range of the available indexes of array.
For example, let's say you have 10 buckets of fruits and all buckets are marked as 0,1,2....,9 serially. So you've got specific identification number for each bucket. So, the last bucket will have the index number total buckets-1 as we've marked them starting from 0, not 1.
So if you say to bring the last bucket, the index number will be always total buckets-1. Again if you try to access the bucket with same index number as total buckets, that will be an invalid query, because you have no such bucket with the index number same as the total number of buckets, in my example, 10. Now look:
for i in range(len(l)):
Here, you're looping from 0
upto the len(l) - 1
(that's how the range(int) works), total l
times, which is the length of the array. Now, when you're trying to deal with the last index number, which is len(l)-1
, then in this specific line:
if l[i] > l[i+1]:
you're trying to access an index len(l)
in the right hand side of the condition, same scenario as my example occurs, you're accessing bucket number 10, which is out of range, hence IndexError: list index out of range
is thrown.
Hope that makes everything clear.