Unable to reverse lists in Python, getting “Nonetype” as list

As jcomeau mentions, the .reverse() function changes the list in place. It does not return the list, but rather leaves qSort altered.

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() with print 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]

>>> a = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[7:] #seventh term and forward
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[:11] #everything before the 11th term
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2] # even indexed terms.  0th, 2nd, etc
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> a[4:17]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> a[4:17:2]
[4, 6, 8, 10, 12, 14, 16]
>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[19:4:-5]
[19, 14, 9]
>>> a[1:4] = [100, 200, 300] #you can assign to slices too
>>> a
[0, 100, 200, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Leave a Comment