[Tutor] to sort

Alan Gauld alan.gauld at btinternet.com
Fri Dec 26 12:59:55 CET 2008


"prasad rao" <prasadaraon50 at gmail.com> wrote 

>     a=[21,56,35,47,94,12]
>      b=[]
> 
>   for x in a:
> b.append (min(a))
> a.remove (min(a))

> It is not Compleating .Doing only 3 rounds.Why?

Think about what is happening.
for x in a

x takes the next value of x after each iteration.
Each iteration reduces the size of a so after 3 iterations 
x will be the 3rd value and there are only 3 values left. 
So x is at the end of the list and the loop stops.

So as Mark said, don't change the list while iterating over 
it - its a bit like cutting off the branch of the tree that you 
are sitting on!

But why are you trying to sort in this fashion? Its 
extremely inefficient compared to using the built in 
methods.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list