I hoped you understood why you got the index out of range error.
That was one of the problems but now let's examine your code because you have some "conceptual" error, in the sense that you are not fully understanding what the code you made does.
This is what your code actually does, and this is how you should think whenever you get errors like this:
sample=[23,44,12,1,6,87]
temp=0
for i in range(0,len(sample)-1):
if sample[i] > sample[i+1]:
temp=sample[i]
sample[i]=sample[i+1]
sample[i+1]=temp
First line:
Your i
will get the values 0,1,2 to 5 (in this case).
Second line:
It will check whether to members of the list that are next to each other.
It will check if the first (from left to right) is bigger that the second, it will check 23 > 44, that will be false, so it won't execute the rest of the code.
No i
will be 1, so you will be checking 44 > 12, this is true, so your code will execute, and successfully swap those two.
This is a good moment to learn a slick way to swap variables in python, without using temporary variables.
sample[i], sample[i+1] = sample[i+1], sample[i]
Read more about it, google python variable swap, if you want.
So back to the original problem.
You have successfully swapped 44 and 12, this list stands [23,12,44,1,6,87]
.
But if you continue to do so it will:
Swap 44 with 1
Swap 44 with 6
Not swap 44 with 87.
But the list will now be [23,12,1,6,44,87]
and your code will stop executing itself because i
is now 5.
Did you catch the problem?
You would need to re-run it several times to actually order it, since it doesn't check whether the list has be organized, rather it swaps members that are next to each other.
So if you would (for this specific list) run:
for j in range(3):
for i in range(0,len(sample)-1):
if sample[i] > sample[i+1]:
sample[i], sample[i+1] =sample[i+1], sample[i]
The list would be ordered.
Sorting ordered collections like lists is a much studied "field".
I would recommend you reading up on sorting algorithms starting by very simple ones, like bubble-sort since that is "where you are going" with your algorithm (like onatm suggested).
There are "fun" ways to learn this algorithm, for example, check this out.
Read up on this too if you are interested.
This site illustrates quite well how the algorithms, work their way to a sorted list.
Good luck, and please comment if you have any doubt.