The sort () and reverse () functions do not work

I tried to check how lists work in python according to the tutorial I read. When I tried to use list.sort() or list.reverse() , the interpreter gives me None .

Please let me know how I can get the result of these two methods:

 a = [66.25, 333, 333, 1, 1234.5] print(a.sort()) print(a.reverse()) 
+5
python sorting list
May 9 '13 at 11:23
source share
4 answers

.sort() and .reverse() change the list in place and return None See the documentation for the mutable sequence :

The sort() and reverse() methods modify the list to save space when sorting or changing a large list. To remind you that they work by side effect, they do not return a sorted or inverted list.

Do this instead:

 a.sort() print(a) a.reverse() print(a) 

or use sorted() and reversed() functions.

 print(sorted(a)) # just sorted print(list(reversed(a))) # just reversed print(a[::-1]) # reversing by using a negative slice step print(sorted(a, reverse=True)) # sorted *and* reversed 

These methods return a new list and leave the original input list intact.

Demo, sorting and reversal in place:

 >>> a = [66.25, 333, 333, 1, 1234.5] >>> a.sort() >>> print(a) [1, 66.25, 333, 333, 1234.5] >>> a.reverse() >>> print(a) [1234.5, 333, 333, 66.25, 1] 

And creating new sorted and inverted lists:

 >>> a = [66.25, 333, 333, 1, 1234.5] >>> print(sorted(a)) [1, 66.25, 333, 333, 1234.5] >>> print(list(reversed(a))) [1234.5, 1, 333, 333, 66.25] >>> print(a[::-1]) [1234.5, 1, 333, 333, 66.25] >>> print(sorted(a, reverse=True)) [1234.5, 333, 333, 66.25, 1] >>> a # input list is untouched [66.25, 333, 333, 1, 1234.5] 
+32
May 09 '13 at 11:24
source share

For reference, you can see the documentation here , in particular, it says:

The sort () and reverse () methods modify the list to save space when sorting or changing a large list. To remind you that they work by side effect, they do not return a sorted or inverted list.

Do not be afraid to read the manual!

+1
May 09 '13 at 12:39
source share

Simple ascending sorting is very simple, call the sorted () function. It returns a new sorted list:

 >>> sorted([66.25, 333, 333, 1, 1234.5]) [1, 66.25, 333, 333, 1234.5] 

sorted () takes an inverse parameter with a boolean value.

 >>> sorted([66.25, 333, 333, 1, 1234.5], reverse=True) [1234.5, 333, 333, 66.25, 1] 
+1
Apr 15 '16 at 9:03
source share

These methods are in place.

This code works (python 3.x)

 a = [66.25, 333, 333, 1, 1234.5] a.sort() print(a) a.reverse() print(a) >>> [1, 66.25, 333, 333, 1234.5] [1234.5, 333, 333, 66.25, 1] 
0
May 9 '13 at 14:48
source share



All Articles