Home > Net >  Python - Why doesn't the reverse function doesn't work when given with list but does work
Python - Why doesn't the reverse function doesn't work when given with list but does work

Time:03-09

Beginner question...

Why does this happen? Why doesn't the reverse function work when given with list but does work with the variable?

>>> a=[1,2].reverse()
>>> a      <--- a is None
>>> a=[1,2]
>>> a.reverse()
>>> a      <--- a is not None and doing what I wanted him to do
[2, 1]
>>>  

CodePudding user response:

It does work. The list reverse method in Python doesn't return reversed list (it doesn't return anything == returns None), it reverses the list it's applied to in place. When you call it on a list literal it is in fact reversed, but there is no way to get the reversed list.

There is reversed function (https://docs.python.org/3/library/functions.html#reversed) that does what you expect

CodePudding user response:

  1. reverse() doesnt return any value,i.e, it returns None.
  2. Reverse() modifies the list in place.

In your first case, you are inturn setting a = None.

In your second case, a is modified by reverse(), and you are able to print the modified "a".

CodePudding user response:

That is because reverse() returns None, but it reverses the order of items in the list.

For example,

>>>a = [1, 2].reverse() # It reversed [1, 2] to [2, 1] but returns None. 
>>>a # The reversed value of [2, 1] disappears, 
# And returned value of None has been assigned to variable a
None
>>>a=[1,2] 
>>>a.reverse() # The order of items of a has been reversed and return None, 
# but there is no variable to take returned value, None.
>>> a
[2, 1]
  • Related