136

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?

6
  • 3
    Using != instead of is not would have made this work, though the if myList form is preferred. Commented May 5, 2010 at 3:13
  • If anyone finds it useful, I created a youtube tutorial comparing the different ways to check if list is empty. API responses are a perfect use case youtube.com/watch?v=8V88bl3tuBQ Commented Jun 27, 2020 at 23:07
  • Why not just process the list? Something like: for item in myList: <do stuff to item> That falls through if the list is empty and if it isn't, you just do whatever you were going to do in the first place. Commented Jul 10, 2020 at 15:42
  • if myList == []: print("The list is empty!") Commented Jan 4, 2021 at 12:03
  • try to use != instead of is not so it'd work Commented Aug 11, 2022 at 11:05

3 Answers 3

210
if not myList:
  print "Nothing here"
Sign up to request clarification or add additional context in comments.

1 Comment

This is the way recommended by PEP8 as Chris Lacasse said in another comment.
23

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"

6 Comments

You can do that, but it would violate pep 8, which says: - For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if not seq: if seq: No: if len(seq) if not len(seq)
Thank you for pointing this out to me, Chris Lacasse. I had no known about pep8, earlier
It would also be a general performance pessimisation: do not spend time counting elements of potentially long collections, if all you need to know is if they are empty.
@AdN: len is an O(1) operation, so that's not really an issue. However, it may be faster (I'm not sure) to simply check if len(myList). Of course, if we head down that way, we may as well do if myList.
And the above will crash if my_list is None
|
20

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.