if list vs if len(list)

In the Python programming language some variables with an ’empty’ value evaluate to False in boolean operations. An integer with value 0, an empty string, an empty set or list, all are evaluated as False.

This can become handy when you want to test wether a list is empty or not. You can just use:

foobar = [1, 2, 3]
if foobar:
    print('foobar is not empty')

An other way of doing this is to check if the list has any length:

foobar = [1, 2, 3]
if len(foobar):
    print('foobar is not empty')

The end result is the same, but way the check works is different. In Python the way of checking is not that different, because the list is actually an array of pointers to the values, and the number of items (length of the array) is stored at in the list head structure. The truth check probably looks at the number of items stored on the list head, and returns True if the number is larger than 0.

Alternative approach

The difference comes when looking at list-like data types, or when using languages that use a different type of list. Consider the following data structure and creating the list:

class MyList:
    next_item = None

    def __init__(self, value=None):
        self.value = value

foo = MyList()
node = foo
for i in range(3):
    node.next_item = MyList(i)
    node = node.next_item

Here we do not store the number of items on the list head, so to get the len(foo) we would have to do:

def length(list_head):
    count = 0
    node = list_head
    while node.next_item is not None:
        count += 1
        node = node.next_item
    return count

Now to get the length of MyList, the code has to go through all items in the list and return the number of items in the list. But to see if there are any items in the list, we could do:

if foo.next_item is not None:
    print('List is not empty')

That saves us a lot of iterating over the list, especially when we have a list that contains a lot of elements.

Conclusion

Does it matter? Not really when using Python native Lists: if foo and if len(foo) both look at the number of elements in the list to determine if it is not empty.

But from a semantic way of programming I still prefer if foo over if len(foo). It indicates to the reader of the code that we are not really interested in the length of the list, only if it contains items.