Search code examples
pythonlistis-empty

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


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.


Solution

  • 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