Last answered:

11 Apr 2022

Posted on:

10 Apr 2022

2

what is " if not self.list_stack: " mean?

what is " if not self.list_stack: " mean?
why it can check if the stack is empty or not?

1 answers ( 0 marked as helpful)
Instructor
Posted on:

11 Apr 2022

4

Hey,

Thank you for your question!

Let me answer it by walking you through the following example. In a new cell in the notebook define an empty list as follows:

list_stack = []

Printing out the list simply returns an empty array. Now, however, try to convert the output in a Boolean format as follows:

bool(list_stack)

Executing this line should output False. Therefore, an empty list converted into Boolean outputs False.

Now, add an element inside the list, for example as follows:

list_stack = [2]

Convert again the list into a Boolean and, this time, the output should be True. Therefore, a non-empty list returns True.

Let's now consider Giles' code. The first line of the is_empty() method reads

if not self.list_stack:

Since the if-statement can only check Boolean values (whether a condition is True or False), self.list_stack will be a Boolean expression. For an empty list, self.list_stack would return False. The not command in front would turn False into True. Therefore, for an empty list, the expression

if not self.list_stack:

would turn into

if not False:

which, in turn, becomes

if True:

Therefore, we enter the if-statement and return True. This is great, as the is_empty() method returns True and we indeed started with an empty list.

Consider now a non-empty list. Then

 if not self.list_stack:

becomes

if not True:

which is equivalent to

if False:

Therefore, we don't enter the if-statement and jump straight to the else-statement. The is_empty() method returns False. This, again, is indeed what we want, since we started with a non-empty list.

Hope the answer helps!

Kind regards,
365 Hristina

Submit an answer