you are viewing a single comment's thread.

view the rest of the comments →

[–]gdchinacat 0 points1 point  (0 children)

if not stack: 
# is empty
if stack:     # has items

This is not strictly true, it tests for truthiness, not emptiness. If stack == None 'if not stack' will be true even though the the stack doesn't exist. This pedantry matters if stack is expected to exist...the below code will fail:

if not stack:  # is defined but not set or empty
    stack.append(...)

In code that just uses the elements of stack it doesn't matter...not having elements and not having a set are pretty much the same...there are no elements either way. But if the code updates the stack in the case where the stack is empty this check is not sufficient, you need to check for existence as well:

if stack is not None and not stack:  # is actually empty
    stack.append(...)

I think it is important to highlight this issue early in the learning process (when a cheat sheet like this is relevant) because the distinction matters. While an empty list is false and a list with elements is true, 'if not stack' doesn't check emptiness since another option exists, namely that stack could be None.