How to check if a list is empty in Python?

PythonList

Python Problem Overview


The API I'm working with can return empty [] lists.

The following conditional statements aren't working as expected:

if myList is not None: #not working
    pass

if myList is not []: #not working
    pass

What will work?

Python Solutions


Solution 1 - Python

if not myList:
  print "Nothing here"

Solution 2 - Python

I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:

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

Solution 3 - Python

Empty lists evaluate to False in boolean contexts (such as if some_list:).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiony2kView Question on Stackoverflow
Solution 1 - PythonMarek KarbarzView Answer on Stackoverflow
Solution 2 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 3 - PythonshylentView Answer on Stackoverflow