The
reverse()
method on a
list
, does return
None
. It's an inline modification of the
list
.
my_list = [1, 2, 3]
my_list = my_list.reverse()
The last line does 3 things:
my_list
is reversed inline
- the reverse() method of
my_list
return None
None
is assigned to the name my_list
- The list, where the name
my_list
pointed before, disappears after the garbage collection
The problem here is a
wrong assumption.
list.sort
and
list.reverse
are inline operations, which modifies the list itself and those operations return
None
.
If you want to sort or reverse an iterable, use
sorted
or
reversed
.
The
sorted
built-in function always returns a
list
.
The reversed function returns a reversed_iterator, which must be consumed by a
list
for example.
my_original_list = [1, 2, 3]
# all following lists do not modify my_original_list
# they are new lists
my_reversed_list_1 = list(reversed(my_original_list))
my_reversed_list_2 = my_original_list[::-1]
# sorting reverse
random_values = [44, 1, -10, 42, 1337, -5, -1, 10, 13, -27]
from_big_to_small = sorted(random_values, reverse=True)
# printing the id for each list object
# they are all different list objects in memory
print(id(my_original_list), id(my_reversed_list_1), id(my_reversed_list_2), sep="\n")
https://docs.python.org/3/library/functions.html#sorted
https://docs.python.org/3/library/functi...l#reversed
https://docs.python.org/3/howto/sorting.html