开发者

Question about reversed lists in Python

开发者 https://www.devze.com 2023-03-01 10:51 出处:网络
I am very new to python, as you will be ab开发者_运维技巧le to tell. If I have a list: a = [1,2,3,2,1]

I am very new to python, as you will be ab开发者_运维技巧le to tell.

If I have a list:

a = [1,2,3,2,1]

This evaluates to true:

a == a[::-1]

...but this evaluates to false:

a == a.reverse()

Why is that the case?


because .reverse() reverses the list in-place and returns none:

>>> print a.reverse()
None

and a == None evaluates to False.


a.reverse() has no return value, so the comparison is a==None which is false

you can check with:

>>> str(a.reversed())
'None'

even better:

>>> (id(a.reverse()), id(None))

you'll see the same addresses


If you want a new copy of the list, use reversed() instead.

a == list(reversed(a))
0

精彩评论

暂无评论...
验证码 换一张
取 消