开发者

reverse() does not work on a Python literal?

Why doesn't this work in Python?

>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse() 
None

I expected to ge开发者_如何学运维t back the list in reverse order.


>>> a = [3, 4, 5]
>>> print a.reverse()
None
>>> a
[5, 4, 3]
>>>

It's because reverse() does not return the list, rather it reverses the list in place. So the return value of a.reverse() is None which is shown in the print.


If you want it to return a new list in reverse order, you can use [::-1]

>>> [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0][::-1]
[0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]

As I'm still trying to understand the downvote, if it doesn't matter that the original list gets changed, use @taskinoor's answer, it'll be faster.

However if you're required to keep the original list unchanged, I suggest you to use [::-1].

from time import time
lst = [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0]

s = time()
for i in xrange(5000000):
    a = lst[::-1]          # creates a reversed list
print time() -s

s = time()
for i in xrange(5000000):
    b = lst[:]             # copies the list
    b.reverse()            # reverses it
print time() -s

outputs

2.44950699806
3.02573299408


If you want reversed copy of a list, use reversed:

>>> list(reversed([1,2,3,4]))
[4, 3, 2, 1]

p.s. reversed returns an iterator instead of copy of a list (as [][::1] does). So it is suitable then you need to iterate through a reversed iterable. Additional list() here used only for the demonstration.


Just to complement other answers. Do not forget:

>> reversed_iterator = reversed([0,1,0,1,1,0,1,1,1,0,1,1,1,1,0])
>> print list(reversed_iterator)
[0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]

This way your list is unchanged if this is a requierement.


reverse changes a list variable as seen here list reverse

if you print it after you reversed it it will show up correctily

so just use a variable

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜