Aleksandr Levchuk
Aleksandr Levchuk

Reputation: 3891

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 get back the list in reverse order.

Upvotes: 18

Views: 2695

Answers (5)

Bertrand Marron
Bertrand Marron

Reputation: 22210

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

Upvotes: 23

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29737

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.

Upvotes: 22

joaquin
joaquin

Reputation: 85673

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.

Upvotes: 3

cwoebker
cwoebker

Reputation: 3288

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

Upvotes: 1

taskinoor
taskinoor

Reputation: 46037

>>> 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.

Upvotes: 52

Related Questions