Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.reverse() is not working [duplicate]

I honestly just don't understand why this is returning None rather than a reversed list:

>>> l = range(10)
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print l.reverse()
None

Why is this happening? According to the docs, I am doing nothing wrong.

like image 627
Ryan Saxe Avatar asked Oct 10 '13 15:10

Ryan Saxe


People also ask

How do you copy a list backwards in Python?

Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.

Why is reverse () returning none in Python?

reverse() method returns None because it reverses the list in place. It doesn't return a new reversed list.

How do you make a reverse list?

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.

Does reversed return a list?

reverse does not return list.


2 Answers

reverse modifies the list in place and returns None. If you do

l.reverse()
print l

you will see your list has been modified.

like image 79
mdml Avatar answered Oct 28 '22 00:10

mdml


L.reverse() modifies L in place. As a general rule, Python builtin methods will either mutate or return something but not both

The usual way to reverse a list is to use

print L[::-1]

reversed(L) returns a listreverseiterator object which is fine for iterating over, but not so good if you really want a list

[::-1] is just a normal slice - the step is -1 so you get a copy starting from the end and ending with the start

like image 41
John La Rooy Avatar answered Oct 28 '22 02:10

John La Rooy