List.reverse () does not work.

I honestly just don't understand why this returns None and not a reverse 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 not doing anything wrong.

+7
python list reverse
source share
4 answers

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

 l.reverse() print l 

You will see that your list has been modified.

+11
source share

list.reverse() cancels the list. It does not return a reverse list. To do this, use reversed() :

 print reversed(l) 

Or just use the extended fragment notation:

 print l[::-1] 
+4
source share

L.reverse() changes L in place. Typically, Python built-in methods will either mutate or return something, but not both

The usual way to cross out the list is to use

 print L[::-1] 

reversed(L) returns a listreverseiterator object , which is great for iteration, but not so good if you really need a list

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

+3
source share

Docs say

list.reverse (): Discard list items in place.

in place means that the original list is being changed, but not returning a new list, so the return you request for printing is None .

0
source share

All Articles