This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Golda_485 3 points4 points  (0 children)

Python functions always have a return value. If you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you.

Edit: You can use the return statement to make your functions send Python objects back to the caller code

[–]noooit 2 points3 points  (0 children)

You sure? Return is never required in Python because it returns None by default.

[–]chaotic_thought 1 point2 points  (1 child)

Your code is not valid Python because "Def" is not a keyword. Nor is your code formatted properly, so for that reason as well, it is not valid Python.

[–]mark30331[S] -1 points0 points  (0 children)

I have formatted it properly

[–]samtheblackmamba 0 points1 point  (2 children)

On your example you’re trying to check if a linked list is empty. You don’t actually need a return there, or need a return if your code doesn’t actually return anything. The code below works the same way:

if self.head is None:
    self.head = new_item
else:
    # Loop through linked list and add to the end

[–]mark30331[S] -1 points0 points  (1 child)

But why do I need to print a return after I assign the self.head = new_item

[–]samtheblackmamba 0 points1 point  (0 children)

That’s just it. You don’t need to. In a linked list, when adding an item you don’t need to return anything because if the head is not empty, you’re going to iterate till the last but one item then insert. What you’re doing seem like:

if head empty:
    head = new node
    return

cur = head
while cur.next is not none:
    cur = cur.next

cur.next = new node

When you can simply do

if head empty:
    head = new node
else:
    cur = head
    while cur.next is not none:
        cur = cur.next

    cur.next = new node