PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] Why does Print() in combination with reverse in Python produce None?

 September 15, 2022     printing, python, reverse     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing