+ 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?
10 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
+ 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
```
+ 1
Don't use list as a name! It reassigns the name and you can't use it to create lists anymore.
+ 1
XXX correction: "The reverse() function" should be "The reversed() function"
+ 1
P.M.
fixed. Also changed "reversed() method" to "reversed() function" because that's more accurate. Thanks for the correction.
+ 1
XXX reversed function reverses the list "in-place"?đ€ man i think you got it wrong again
+ 1
P.M.
does "in-place" not mean reverse then-and-there and return the reversed one? If not, what should I write?
+ 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
+ 1
"what should I write?"
you could write "to return a reversed copy of the list" instead of "to reverse the list in-place"