-6

Whenever I use list methods in the print function, it gives none as an output, but if I apply methods and store in it variable before print() and then print that variable, only it will provide the desired result. Why? Let me show you what I am talking about:

l = [9, 4, 7, 1, 2]

print(l.sort())

None

But tuple can give the output in the print function.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • Welcome to Stack Overflow. Please paste code here as [formatted text](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks), not as [images](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question). – CrazyChucky Jul 02 '22 at 10:55
  • 2
    The fact that `.sort()` does not return a value and instead modifies the list in-place [is well-documented behavior.](https://docs.python.org/3/library/stdtypes.html#list.sort) have you tried to refer to the documentation before posting? – esqew Jul 02 '22 at 10:56
  • Go to this [Link](https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python) for a full description. – sadegh arefizadeh Jul 02 '22 at 10:58
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jul 02 '22 at 12:21

1 Answers1

1

List methods are indeed functions that modify the value of the Python list. These functions don't return any value because their purpose is to perform operations directly on the corresponding list values.

However, there are some special build-in functions like sorted() as you can see in the following example, which return the modified list, instead of just changing its values and returning None :

> l = [9, 4, 7, 1, 2]

> print(l.sort())
None
> print(sorted(l))
[1, 2, 4, 7, 9]

When you invoke list.sort(), the list is sorted but if you try to print the outcome of the function, you will find that the function is not coded to give any out value, so you will get None. As shown in the question comments, you can learn more about this behavior on the official Python documentation.

robertwb
  • 4,891
  • 18
  • 21
Cardstdani
  • 4,999
  • 3
  • 12
  • 31