Issue
I have just come across an interesting case, I think.
I was trying to reverse my list and then print output using the print()
function.
Here are the two ways I have tried:
1. Printing directly:
x = [2.0, 9.1,12.5]
print(x.reverse())
output: None
2. Using f string:
x = [2.0, 9.1,12.5]
print(f"The reverse of x is {x.reverse()}")
output: The reverse of x is None
The output from both methods is None
as you can see above.
Can anyone explaing why both methods produce None
?
P.S. I know that the this method works and prints revered list
x.reverse()
print(x)
but I am not intereseted in this? I want to find out why both methods above produce None
.
Solution
x.reverse()
is a so called in-place operation, that means the list stored in the variable x
is modified (reversed) and the output of x.reverse()
is None
. Hence, when you run print(x.reverse())
it prints the output which in this case it None
.
P.S.
If you need an operation which returns a reversed copy of the original list, you can use reversed()
more info here:
x = [2.0, 9.1, 12.5]
print(list(reversed(x)))
(Note: list
is used to convert the iterator result of reversed
to a list).
The second option is to create a reversed copy via slicing (thanks @Andrey):
x = [2.0, 9.1, 12.5]
print(x[::-1])
More context:
In general, in-place operations return None
, that helps prevent mistakes and distinguish in-place and normal operations.
Answered By - mikulatomas Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.