Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading