1

As I was solving problems on Linked Lists,

I write: while head1 != None and head2 != None:

and people write: while head1 and head2:

Both while statements do the same job, but I don't really understand how it works!!!

why does the while loop take head != None by default even when I don't mention it?

`# An example code I was working on def mergeLists(head1, head2):

head3 = SinglyLinkedListNode(-1)

node = head3

while head1 and head2: **# Here I usually mention != None**
    
    if head1.data < head2.data:
        node.next = head1
        head1 = head1.next
        
    else:
        node.next = head2
        head2 = head2.next
        
    node = node.next
    
if head1: **# Also down here != None, but it works without it and I need to understand why**
    node.next = head1

if head2:
    node.next = head2
    
return head3.next`
Akash Saha
  • 11
  • 1
  • 1
    Not strictly a duplicate, but [this post](https://stackoverflow.com/q/39983695/6340496) might help explain the concept of *truthiness*. Additionally, a `None` test should use the `is` / `is not` object comparison operators, *not* the `==` / `!=` equivalency operators. – S3DEV May 24 '23 at 12:13
  • 1
    For clarity, this `while head1 and head2:` is the correct approach. – S3DEV May 24 '23 at 12:15

0 Answers0