I have a .py file that takes a list, finds the lowest number, puts it into a new array, removes the lowest number from the first array, and repeats until the original array returns contains no more items:
def qSort(lsort):
listlength = len(lsort)
sortedlist = list()
if listlength == 0:
return lsort
else:
while listlength > 0:
lmin = min(lsort)
sortedlist.append(lmin)
lsort.remove(lmin)
listlength = len(lsort)
return sortedlist
Now another .py file imports the qSort and runs it on some list, saving it to a variable. Then I try to use the .reverse() command on the list and I end up getting it as a NoneType. I try to use reversed(), but all it does is say "<listreverseiterator object at 0xSomeRandomHex>":
from qSort import qSort #refer to my first Pastebin
qSort = qSort([5,42,66,1,24,5234,62])
print qSort #this prints the sorted list
print type(qSort) #this prints <type 'list'>
print qSort.reverse() #this prints None
print reversed(qSort) #this prints "<listreverseiterator object at 0xSomeRandomHex>"
Can anyone explain why I can’t seem to reverse the list, no matter what I do?
As jcomeau mentions, the
.reverse()function changes the list in place. It does not return the list, but rather leavesqSortaltered.If you want to ‘return’ the reversed list, so it can be used like you attempt in your example, you can do a slice with a direction of -1
So replace
print qSort.reverse()withprint qSort[::-1]You should know slices, its useful stuff. I didn’t really see a place in the tutorial where it was all described at once, (http://docs.python.org/tutorial/introduction.html#lists doesn’t really cover everything) so hopefully here are some illustrative examples.
Syntax is:
a[firstIndexInclusive:endIndexExclusive:Step]