I feel a little bit silly asking this, but I'm practicing some DSA. I'm watching a Youtube video, and I find odd that in some methods of the class the return method is left without returning a value. I know that it'll return None
but I don't understand how the code works.
Here's the code snippet:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def to_list(self):
out = []
node = self.head
while node:
out.append(node.value)
node = node.next
return out
### In the following method is my doubt ###
def prepend(self, value):
""" Prepend a value to the beginning of the list. """
if self.head is None:
self.head = Node(value)
return # Why is this return value left alone without returning anything?
new_head = Node(value)
new_head.next = self.head
self.head = new_head
return # Why is this return value left alone without returning anything?
LinkedList.prepend = prepend
Can someone please explain to me, what is this code doing, because as I understand the prepend
method is working with two None values from the 2 empty returns.
CodePudding user response:
A return
is used when you want to stop a function from executing further. The first one is necessary in order to not have the statements after the if self.head is None
block be executed. The second one is unnecessary, as it's at the end of the function, so the function will return regardless. It's just a more explicit way of saying "I am returning here, but am not returning anything". That's the default behavior of any function that you don't explicitly put a return
into.
It's very common in programming languages to have explicit, blank returns. For instance in C, any function whose return type is void
has to have any return
s be empty. In Python there's tons of built-in functions that don't need to return anything, let alone all the custom ones one might create. For instance, list.append()
returns None
; which is what any function in Python returns by default when there's not anything explicitly being returned.
CodePudding user response:
The first return
in prepend
is an early return and this is the only way of returning from this point in the function as it is currently written.
The second return is entirely redundant and can be removed.
CodePudding user response:
It is just a matter of style, whether one just lets the function-body end returning None implicitly, writes a naked return statement or even writes return None
explicitly. These are all functions which return None:
def a():
pass
def b():
return
def c():
return None
However the first method does not allow you to return early. This is why an explicit return is needed in the if branch of the method. Otherwise control flow would continue and prepend the same value twice.
The second return statement at the end is redundant.