'Python - Why doesn't the reverse function doesn't work when given with list but does work with the variable? [duplicate]
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]
>>>
Solution 1:[1]
- reverse() doesnt return any value,i.e, it returns None.
- 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".
Solution 2:[2]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | apoorva kamath |
| Solution 2 | Park |
