Why can't I use .reverse on a specific range in a list python?

Question:

I am writing a simple script, where I have a list of character and I want to loop over this list and reverse the ordered of 3 elements at a time. Ex. List: a,b,c,d,e,f ; Reversed list: c,b,a,f,e,d.

I tried to use
print(list[0:2].reverse())
however when I tried printing this it outputted NONE
My question is why does this happen?

FYI: I know there are other ways of doing this, I am just curious as to why this did not work.

Asked By: mshark

||

Answers:

lst[0:2].reverse()

does not do much to the original list lst, because the slice operation lst[0:2] returns a new independent list object which is then reversed in-place by reverse. The original lst is unimpressed by this. You have to feed the reversed slice back with slice assignment to mutate the original. E.g.:

lst[0:2] = lst[0:2][::-1]

You could also use list.reverse‘s brother reversed , which does return an object (an reverse order iterator):

lst[0:2] = reversed(lst[0:2])
Answered By: user2390182

When you do a slicing operation e.g list[0:2], you essentially create a new list

Since reverse operates on the object you give it, but doesn’t return anything, if you were to do print(list.reverse()) it would still print None because reverse doesn’t return anything, but modify the object you use it on.

Now, since slicing creates a new list, when you do list[0:2].reverse() , you are modifying the list created by the slicing, which is also immediately lost since you don’t assign it to any variable (and you can’t since reverse doesn’t return a value). Essentially, you are creating a list with the slicing, modying it, and then losing it forever

Additionally, you can assign the slicing to a variable and then use reverse on it, but it wouldn’t be useful in your case

listed= ["a", "b", "c", "d", "e", "f"]
sliced = listed[0:2]
sliced.reverse()
print(sliced) prints ['b', 'a']

Hope this is clear

(Last advice, don’t call your list "list", it shadows the built-in name)

Answered By: Sparkling Marcel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.