pythonlist

Why does Python return None on list.reverse()?


I was solving an algorithms problem and had to reverse a list. When done, this is what my code looked like:

def construct_path_using_dict(previous_nodes, end_node):
    constructed_path = []
    current_node = end_node
    while current_node:
        constructed_path.append(current_node)
        current_node = previous_nodes[current_node]
    constructed_path = reverse(constructed_path)    
    return constructed_path

But, along the way, I tried return constructed_path.reverse() and I realized it wasn't returning a list.

Why was it made this way?

Shouldn't it make sense that I should be able to return a reversed list directly, without first doing list.reverse() or list = reverse(list) ?


Solution

  • You're asking why the reverse method doesn't return a (reference to the) result, and instead modifies the list in-place. In the official python tutorial, it says this on the matter:

    You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

    In other words (or at least, this is the way I think about it) - python tries to mutate in-place wherever possible (that is, when dealing with an immutable data structure), and when it mutates in-place, it doesn't also return a reference to the list - because then it would appear that it is returning a new list, when it is really returning the old list.

    To be clear, this is only true for object methods, not functions that take a list, for example, because the function has no way of knowing whether or not it can mutate the iterable that was passed in. Are you passing a list or a tuple? The function has no way of knowing, unlike an object method.