Python empty list - How to check if a list is empty

Python list may be empty and there are many ways to check if a list is empty or not. The below code follows the standard Python coding convention (PEP).

a = [2, 3, 5]
b = []

if a:
    print('a is Good')
else:
    print('a is Bad')

# a is Good

if b:
    print('b is Good')
else:
    print('b is Bad')

# b is Bad

It is recommended that you simply use if ... statement to check a list is empty.

Bad example

In fact, you can check if an object is list by counting the number of items. If it is 0, the list may be empty.

b = []

if 0 < len(b):
    print('b is Good')
else:
    print('b is Bad')

# b is Bad

But this is not pythonic and not recommended.

Index of empty list

Empty list has no index.

a = []

b = a[0]

# IndexError: list index out of range

Compare empty lists

In Python, empty lists are the same.

a = []
b = []

if a == b:
    print('a is b.')
else:
    print('a is not b.')

# a is b.

But ids of them are completely different. Python id represents the identity or memory address of an object. As you can see, ids of empty lists are different.

a = []
b = []

print(id(a))  # 4529691520
print(id(b))  # 4529692224

As explained in this post, the same values (int, float, ...) have the same ids but it is not true for lists and empty lists.

Comments

Powered by Markdown

More