Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

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]

Solution 2:

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.

Solution 3:

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

Solution 4:

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()

Solution 5:

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]

Post a Comment for "Python A = A.reverse Makes The List Empty?"