Q:

python: "while (len(list1)>0) or (len(list2)>0)" doesn't work

Im taking the Google Python Course and I am solving the below problem:

Given two lists sorted in increasing order, create and return a merged >list of all the elements in sorted order. You may modify the passed in >lists. Ideally, the solution should work in "linear" time, making a single >pass of both lists.

And my solution is below:
def linear_merge(list1, list2):
    # +++your code here+++
    a = []
    while (len(list1)>0) or (len(list2)>0):
        if list1[-1] > list2[-1]:
            a.append(list1.pop(-1))
        elif list1[-1] < list2[-1]:
            a.append(list2.pop(-1))
        else:
            a.append(list1.pop(-1))
            a.append(list2.pop(-1))
     #Have to force check
        if (len(list1)==0):
            break
        if (len(list2)==0):
            break
    if len(list1)>0:
        res = (a+list1)
        return res[::-1]
    else:
        res = (a+list2)
        return res[::-1]

My issue is even though I check if both lists are empty, I get a list index out of range error. I have to force check if either list is empty at the end of the while loop to prevent the error from occurring.
Why is the while loop failing to correctly see that one of the lists is empty? I am new to python and I am looking for some clarification on why this happens.

A:

My issue is even though I check if both lists are empty...

No, you are checking if either one of them is not empty.

Change this:
while (len(list1)>0) or (len(list2)>0)

To this:
while (len(list1)>0) and (len(list2)>0)

And at the end of the while loop continue working on the one list which is still not empty.

