I was trying to test how the lists in python works according to a tutorial I was reading.
When I tried to use list.sort()
or list.reverse()
, the interpreter gives me None
.
Please let me know how I can get a result from these two methods:
a = [66.25, 333, 333, 1, 1234.5]
print(a.sort())
print(a.reverse())
Example 2: Sort in descending order The sorted() function accepts a reverse parameter as an optional argument. Setting reverse = True sorts the iterable in the descending order.
Sort in Descending orderThe sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order.
Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list. So in your case answer = sorted(newList) .
.sort()
and .reverse()
change the list in place and return None
See the mutable sequence documentation:
The
sort()
andreverse()
methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
Do this instead:
a.sort()
print(a)
a.reverse()
print(a)
or use the 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 untouched.
Demo, in-place sorting and reversing:
>>> 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 reversed 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]
A simple ascending sort is very easy, 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() accept a reverse parameter with a boolean value.
>>> sorted([66.25, 333, 333, 1, 1234.5], reverse=True)
[1234.5, 333, 333, 66.25, 1]
For reference, you can see the documentation here specifically says:
The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
Don't be afraid to read the manual!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With