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.
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.
reverse() method returns None because it reverses the list in place. It doesn't return a new reversed 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.
reverse does not return list.
reverse
modifies the list in place and returns None
. If you do
l.reverse()
print l
you will see your list has been modified.
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
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