134

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?

hygull
  • 8,464
  • 2
  • 43
  • 52
y2k
  • 65,388
  • 27
  • 61
  • 86
  • 2
    Using `!=` instead of `is not` would have made this work, though the `if myList` form is preferred. – Mike Graham May 05 '10 at 03: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 https://www.youtube.com/watch?v=8V88bl3tuBQ – Brendan Metcalfe Jun 27 '20 at 23:07
  • Why not just process the list? Something like: for item in myList: 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. – MrWonderful Jul 10 '20 at 15:42
  • `if myList == []: print("The list is empty!")` – anjandash Jan 04 '21 at 12:03
  • try to use `!=` instead of `is not` so it'd work – Léo Aug 11 '22 at 11:05

3 Answers3

209
if not myList:
  print "Nothing here"
Marek Karbarz
  • 28,956
  • 6
  • 53
  • 73
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"
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 36
    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) – Chris Lacasse Nov 12 '09 at 22:16
  • Thank you for pointing this out to me, Chris Lacasse. I had no known about pep8, earlier – inspectorG4dget Nov 14 '09 at 00:53
  • 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. – Ad N Aug 12 '15 at 12:38
  • 1
    @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`. – inspectorG4dget Aug 12 '15 at 22:44
  • 2
    And the above will crash if my_list is None – rkachach Feb 25 '16 at 11:07
  • When it comes to Django Rest Framework I had to use this approach to check if a list was empty BUT Defined on the request body, if it was not I needed other error, using the boolean approach overrode the "Field Not Defined error" – Dr Jfrost Feb 18 '22 at 21:23
20

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

shylent
  • 10,076
  • 6
  • 38
  • 55