Computer Science // Linked List // while current_node:

Hi! I’m doing the Computer Science fundamentals in Python. Linked Lists. Did find with the conceptual parts but creating a class to implement linkedlists was extremely confusing.

Quick question. for the stringify_list method, does ‘while current_node:’ have the meaning of, “while current node is not null, do the following”? thanks!

def stringify_list(self):
string_list = “”
current_node = self.get_head_node()
while current_node:
if current_node.get_value() != None:
string_list += str(current_node.get_value()) + “\n”
current_node = current_node.get_next_node()
return string_list

Yes, you’ve got it! You can see later in the stringify function that we’re reassigning the initial value of current_node from being the head node to the next node in the list which will eventually run into a null value and close the while loop.

1 Like

Thanks! that threw me for a loop as I’d never seen that behavior before from a while loop. but the rest of the code makes now that I’m over that speedbump :slight_smile:

2 Likes

It’s kind of glossed over in many places but it works like an if statement does and evaluates the ‘truthiness’ of the expression.

In this case current_node would evaluate to True unless current_node was None which evaluates to False (you can use bool(current_node) f you wanted to test this).

You can find some details on this around but things like 0, None and empty sequences e.g. [] or tuple() all evaluate to False. Potentially useful link below but there’s guidance elsewhere if you prefer-
https://www.pythonmorsels.com/topics/truthiness/

1 Like

:joy::joy::joy: that is an awesome tip, thank you!

1 Like