Last updated: Apr 10, 2024
Reading timeยท2 min
The list.reverse()
method returns None
because it mutates the original
list. Most methods that mutate an object in place return None
in Python.
a_list = ['bobby', 'hadz', '.', 'com'] result = a_list.reverse() print(result) # ๐๏ธ None print(a_list) # ๐๏ธ ['com', '.', 'hadz', 'bobby']
The list.reverse() method reverses the elements of the list in place.
The method returns None because it mutates the original list.
None
.If you want to reverse the list without mutating it in place, use the
reversed()
function.
a_list = ['bobby', 'hadz', '.', 'com'] result = list(reversed(a_list)) print(result) # ๐๏ธ ['com', '.', 'hadz', 'bobby'] print(a_list) # ๐๏ธ ['bobby', 'hadz', '.', 'com']
The reversed() function takes an iterator, reverses it and returns the result.
list()
class to convert the iterator to a list.The reversed()
function doesn't mutate the original list. The original list
remains unchanged.
You can also reassign the variable if you don't need to keep the original list around.
a_list = ['bobby', 'hadz', '.', 'com'] a_list = list(reversed(a_list)) print(a_list) # ๐๏ธ ['com', '.', 'hadz', 'bobby']
Alternatively, you can use the
list slicing syntax with a step
of -1
to reverse the list and return the result.
a_list = ['bobby', 'hadz', '.', 'com'] result = a_list[::-1] print(result) # ๐๏ธ ['com', '.', 'hadz', 'bobby'] print(a_list) # ๐๏ธ ['bobby', 'hadz', '.', 'com']
The syntax for list slicing is my_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
If the start
index is omitted, it is considered to be 0
, if the stop
index
is omitted, the slice goes to the end of the list.
step
of -1
to reverse the list. When a negative step is used, we select every Nth element from the end of the list toward the beginning.Negative indices can be used to count backward, e.g. my_list[-1]
returns the
last item in the list and my_list[-2]
returns the second to last item.
You can reassign the a_list
variable if you don't need to keep the original
list around.
a_list = ['bobby', 'hadz', '.', 'com'] a_list = a_list[::-1] print(a_list) # ๐๏ธ ['com', '.', 'hadz', 'bobby'] print(a_list) # ๐๏ธ ['bobby', 'hadz', '.', 'com']
Don't try to assign the result of calling reverse()
, append()
, insert()
or
extend()
to a variable because methods that mutate the original object most
commonly return None
.
Most of the time, you can hover over the method in your IDE to see the method's return value.
If a method returns None
, then it mutates an object in place.
Conversely, most methods that return a value other than None
, usually return a
new object and don't mutate the original one.