None clarification


I recently went over a lesson on None; however, I am still not entirely clear on its functionality. Could anyone provide some examples for when I could expect to get None as the result of running some code?
For example, I am not understanding why the code below would return None both times…

print_return = print('Hello')
#prints hello 
#prints None 

#but why!! should this not be the same as the line above?#

sorted_this_list [5,7,3,2]
list_sort_return = sort_this_list.sort()

#prints None

#why does this not print the sorted list?

Also, this is somewhat unrelated, but how is it that None is its own type?!
That is when I typed print(type(None)) I got <class 'NoneType> in the terminal!

Thanks in advance for considering my questions!

1 Like

What else would it be? It is simply the type which means nothing. It isn’t a string (you don’t wrap it in ""), it isn’t an integer, and booleans can only have False or True as their values…

The function print() does not return anything. When you write a function, say:

def some_func():
  return "Hello, world!"

The data (in this case a string-"Hello, world!") is handed back to the part of your program which called the function some_func(). In the case of print(), it returns nothing, therefore, kind of by default, returns None. So, in the first line where you write print_return = print('Hello'), the print() function is called, and therefore prints the string, but returns nothing (None), meaning the value stored in print_return in now None. Therefore, when you print print_return, you get None.

Similarly, in your second example, the .sort() method doesn’t actually return anything; it modifies the list in place. Here is a very good article on the .sort() method.

If you want to sort a list and have that sorted list returned, the sorted() method could be used:

some_list = [2, 3, 4, 1]
sorted_some_list = sorted(some_list)
#prints [1, 2, 3, 4]

Thanking for clearing up my confusion!

1 Like