1

I have this function for linked lists in Python3:

    def search_list(L: ListNode, key: int) -> ListNode:
       while L and L.val != key:
          L = L.next
       return L

So my question is what is the difference between the above and:

    def search_list(L: ListNode, key: int) -> ListNode:
       while L != None and L.val != key:
          L = L.next
       return L

Is there a difference?

Is the first way of writing it is just saying: "while L is not NULL/None and L.val does not equal key, keep the loop running?"

Any help is appreciated, thanks.

1 Answers1

3

if L: checks if L is truthy.
if L != None checks if L is not None.

The biggest difference would be when L is False.
The former won't execute because it is if False.
The latter will execute because False != None is true.

In your use case it won't make any difference.
But be aware of how "truthy" and "falsy" values work in if/while expressions because they do make big difference in certain cases.

WieeRd
  • 792
  • 1
  • 7
  • 17
  • 4
    I'll just add that the Pythonic way to check against `None` or any other singleton is `if L is not None:` instead of `if L != None:`. This is because the = and != operators can be overloaded but the `is` operator can not. – nigh_anxiety Jun 22 '22 at 05:00
  • 1
    Using `is not None` is particularly important with NumPy arrays, where trying to use `if arr` or `if arr != None` will usually give a TypeError due to how NumPy arrays handle `__ne__` and `__bool__`. – user2357112 Jun 22 '22 at 05:03