Sumod
Sumod

Reputation: 3846

Python a = a.reverse makes the list empty?

At the interpreter,

a = [1,2,3,4]
a = a.reverse()

Next when I type a at the interpreter, I get nothing. So it seems a = a.reverse() generates an empty list. Is this by design?

I am using python 2.5 on windows xp.

Upvotes: 3

Views: 3525

Answers (7)

utdemir
utdemir

Reputation: 27216

list.reverse() modifies the list in-place, returns None. But if you want to protect old list, you can use reversed() function for that, it returns an iterator.

In [1]: a=[1,2,3,4]

In [2]: print(a.reverse())
None

In [3]: a
Out[3]: [4, 3, 2, 1]

In [4]: a=[1,2,3,4]

In [5]: print(reversed(a))
<listreverseiterator object at 0x24e7e50>

In [6]: list(reversed(a))
Out[6]: [4, 3, 2, 1]

In [7]: a
Out[7]: [1, 2, 3, 4]

Upvotes: 18

Michael
Michael

Reputation: 9058

list.reverse() just doesn't return anything, because it changes the list in-place. See this example:

>>> a = [1,2,3,4]
>>> a.reverse()
>>> a
[4, 3, 2, 1]

There also is the reversed function (actually a type, but doesn't matter here), which does not change the list in-place, but instead returns an iterator with the list items in the reverse order. Try:

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

Upvotes: 1

JMD
JMD

Reputation: 228

The reverse method does the reverse 'in place' (like sort) and returns None, so after calling a.reverse() a already contains the result.

Upvotes: 0

pconcepcion
pconcepcion

Reputation: 5641

I think what you want to do is:

a = [1,2,3,4]
a.reverse()

a is an object and the operations work on it's data, so you don't need to assign again it.

Upvotes: 0

Gabriel L. Oliveira
Gabriel L. Oliveira

Reputation: 4072

The built-in method reverse of a list on python doesn't return the reversed list.

It reverses the list in place.

So, if you want to reverse your list, like in your code, just do:

a = [1,2,3,4]
a.reverse()

Upvotes: 1

Amadan
Amadan

Reputation: 198314

reverse changes list in-place, and doesn't return anything. Thus, this is the expected usage:

a = [1, 2, 3, 4]
a.reverse()
a       # => [4, 3, 2, 1]

If you assign the result of reverse back to a, you will overwrite all its hard work with the nonsensical return value (None), which is where your bug comes from.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798636

list is a mutable type, so list operations are in-place, and return None.

Upvotes: 1

Related Questions