(list.reverse()!=list[::-1] ) why??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

(list.reverse()!=list[::-1] ) why???

Hi, I realized that these are not equal. Why? list.reverse()!=list[::-1] If we put this equal in the if condition, false is reported. Why is it false when the output of both is equal?

9th May 2021, 8:35 AM
Marjaf
Marjaf - avatar
9 Answers
+ 8
list.reverse() doesn't return anything. It reverse the original list. But list[::-1] returns the reversed list and doesn't change anything in original list. While list.reverse() make changes to original list and return None list = [1,2,3] list.reverse() == list[::-1] None == [3,2,1] You are doing this in above line of code
9th May 2021, 9:08 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 3
Adding to what the others have said, you can use the reversed() function to return a reversed copy of the list. The reversed() function returns an iterator, so you'll have to pass it to the list() constructor to create a list of it. Example ``` lst = [1, 2, 3] print(list(reversed(lst)) == lst[::-1]) # prints True ```
9th May 2021, 9:16 AM
XXX
XXX - avatar
+ 1
Don't use list as a name! It reassigns the name and you can't use it to create lists anymore.
11th May 2021, 7:01 AM
Thoq!
Thoq! - avatar
+ 1
XXX correction: "The reverse() function" should be "The reversed() function"
12th May 2021, 1:31 PM
Bot
Bot - avatar
+ 1
P.M. fixed. Also changed "reversed() method" to "reversed() function" because that's more accurate. Thanks for the correction.
12th May 2021, 4:40 PM
XXX
XXX - avatar
+ 1
XXX reversed function reverses the list "in-place"?🤔 man i think you got it wrong again
12th May 2021, 5:02 PM
Bot
Bot - avatar
+ 1
P.M. does "in-place" not mean reverse then-and-there and return the reversed one? If not, what should I write?
12th May 2021, 5:11 PM
XXX
XXX - avatar
+ 1
XXX no, in-place means no external copy of the data is made. that often means that you need to work with the data and in doing so you are changing the data reversed() function makes a reversed copy of the data it and returns it and so isnt in-place. while reverse() method changes the list its called on and so doesnt need to make another copy of the list, and so is in-place
12th May 2021, 5:41 PM
Bot
Bot - avatar
+ 1
"what should I write?" you could write "to return a reversed copy of the list" instead of "to reverse the list in-place"
12th May 2021, 5:44 PM
Bot
Bot - avatar