required help in manual sort

Peter Otten __peter__ at web.de
Mon Mar 7 05:26:41 EST 2011


Manjunath N wrote:

> Hello users,
>      I'm quite new to python programming.  I need help in manually sorting
>      a
> list which is shuffled.  The problem i'm facing is with respect to last
> element in the list when checking the condition using if statement. Below
> I have pasted my code. The code is below is not yet done, at first I am
> trying
> to separate the number as lower and higher.  I just need help here.
> 
> import random, pdb
> 
> pdb.set_trace()
> 
> unordered=range(10)
> random.shuffle(unordered)
> ordered=[]
> 
> print "The unordered selection of list is\n",unordered,"\n"
> 
> unordered_len=len(unordered)
> higher=[]
> lowest=[]
> a=1
> 
> for i in unordered:
>     if i<unordered[a]:
>         lowest.append(i)
>         a+=1
>     elif i > unordered[a]:
>         higher.append(i)
>         a+=1
> 
> print "\n\n\nLowest",lowest
> print "\n\nHighest",higher
> 
>  When I run the program, I get the error message as,
> line 16, in <module>
>     if i<unordered[a]:
> IndexError: list index out of range
> 
> I know that the error is happening because when variable 'i' comes to the
> last element in the unordered list, it doesnt have anyother variable for
> checking the condition if i<unordered[a]: .  But i'm not able to handle
> this condition in the code.
> 
> So someone please help in this regards.

You are mixing values in the unordered list with indices into that list. If 
you start with non-integers as values, e. g.

unordered = list("abcdefghij")
...

it will be easier for you to avoid the confusion.

Also, did you know that list indices start with 0, not 1?





More information about the Python-list mailing list