Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does sorting of a list work outside of, but not within the print function in Python?

I have a list in Python which I want to sort by alphabet.
If I do this directly within the the print() function, it yields "None", while it works fine if I sort it first and then print it. Here is the reproducible code:

def main():
    l = ["Tina", "Alice"]
    print(l.sort())
    # yields "None"
    
    l.sort()
    print(l)
    # yields ["Alice", "Tina"]
    
if __name__ == "__main__":
    main()

Can someone explain to me what the difference is in the background for Python? Some other operations like adding numbers etc. work fine within the print() function. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s because sort function returns None, it modifies the list itself.

There are sorted function too, which doesn’t modify list but returns new one

print(sorted(l))

For more information look here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading