0

I was trying to solve a problem: find middle node of a linked list with following code ( and it works)

s = f = head
while f and f.next:
  s = s.next
  f = f.next.next
return s

but when I accidentally wrote this it failed:

        s = f = head
        while f.next and f:
            s = s.next
            f = f.next.next
        return s

with error

AttributeError: 'NoneType' object has no attribute 'next'
    while f.next and f:

I am trying to find out why this behavior, both loops check if f and f.next are not None. why order matters here?

  • 1
    Boolean `and` short circuits, meaning if the first condition is `False` the second condition is never checked. In your second test you check `f.next` before checking if `f` is `None`. In the first you check `if f` first so if it's `None` `f.next` is never attempted and you don't get the error. – Mark Jan 22 '23 at 04:39
  • https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting – Pranav Hosangadi Jan 22 '23 at 05:07

0 Answers0