Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list is empty in Python? [duplicate]

Tags:

python

list

People also ask

How do I check if a list is empty in Python?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.

How do you check if a number is repeated in a list Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.

How do I check if a 2d list is empty in Python?

You can check if the list is empty in python using the bool() function. bool() function returns boolean value of the specified object. The object will always return True , unless the object is empty, like [] , () , {} . You can use the bool function for any of the list-like objects.

How do you check if a list is empty or null?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.


if not myList:
  print "Nothing here"

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


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"