Check if list is empty without using the `not` command

user2240288 picture user2240288 · Apr 15, 2013 · Viewed 71.1k times · Source

How can I find out if a list is empty without using the not command?
Here is what I tried:

if list3[0] == []:  
    print("No matches found")  
else:  
    print(list3)

I am very much a beginner so excuse me if I do dumb mistakes.

Answer

John Kugelman picture John Kugelman · Apr 15, 2013

In order of preference:

# Good
if not list3:

# Okay
if len(list3) == 0:

# Ugly
if list3 == []:

# Silly
try:
    next(iter(list3))
    # list has elements
except StopIteration:
    # list is empty

If you have both an if and an else you might also re-order the cases:

if list3:
    # list has elements
else:
    # list is empty