Python: How to check if two lists are not empty

listpython

In Python, I know the pythonic way to check if a list is empty is

if not a:
    # do things with empty list

To check if a list is not empty then, we would do:

if a:
    # do things with my list

How would we check, simultaneously (as read), if two lists then are not empty?

if a and b:
    # do things with my two lists

The above does not seem to work, and I'm unsure what (a and b) actually means. For a = [2], b = [1,3], (a and b) = [1,3]. What is the and operator actually doing here? If I end up reducing b = [] at some point, (a and b) = [] even though a is not empty.

Edit: My use case goes something like

while (a and b are not empty):
    modify a
    modify b

I would have naively thought that since if a checks if a list is not empty, if a and b would check if neither were empty, which is not the case.

Best Solution

It's working fine. For a = [2] and b = [1, 3], a and b is returning [1, 3] which is truthy, exactly as you would expect, because True and True is True. When you change b to [] it returns [], which is falsy, again exactly as you would expect, because True and False is False. So if a and b does exactly what you want.

What is actually happening is that and is returning the value that decided the truth of the expression. and doesn't always evaluate both sub-expressions; when the first is falsy, the whole expression is falsy and the second doesn't need to be evaluated, and therefore isn't. This is called short-circuiting. or behaves similarly (skipping evaluating the second part if the first part is truthy). Wherever and or or is able to make its decision, it returns that value.

Another way of looking at it: bool(a) and bool(a) == bool(a and b) in Python.