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!
>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