how to Check if a List is Empty in Python?

In Python, you can check if a list is empty using several methods. Here are some common ways to do it:

Using the not keyword

In Python, empty containers (like lists, tuples, sets, dictionaries, etc.) are considered False in a boolean context. Therefore, you can use the not keyword to check if a list is empty.

Example:

lst1 = []
lst2 = [1, 2, 3]

if not lst1:
    print("lst1 is empty")

if not lst2:
    print("lst2 is empty")
else:
    print("lst2 is not empty")

Output:

lst1 is empty
lst2 is not empty

Using the len() function:

The len() function returns the number of items in an object. When applied to a list, it returns the number of elements in the list.

Example:

lst1 = []
lst2 = [1, 2, 3]

if len(lst1) == 0:
    print("lst1 is empty")

if len(lst2) == 0:
    print("lst2 is empty")
else:
    print("lst2 is not empty")

Output:

lst1 is empty
lst2 is not empty

Comparing with an empty list

You can directly compare a list with an empty list ([]) to determine if it’s empty.

Example:

lst1 = []
lst2 = [1, 2, 3]

if lst1 == []:
    print("lst1 is empty")

if lst2 == []:
    print("lst2 is empty")
else:
    print("lst2 is not empty")

Output:

lst1 is empty
lst2 is not empty

In general, the first method (not keyword) is the most idiomatic in Python and is often preferred because it’s concise and can be used with other container types without modification. The len() method is explicit and may be more readable for those new to Python or in situations where the explicitness adds clarity. The comparison with an empty list is less common but can be used if you’re sure you’re working with a list (and not another type of iterable).