I would like to know what would be the best way to check if a list is empty.
I know this question seems silly, but I realize that sometimes when you are working with others and others read your code, using certain functions may look better than others, and would be more understandable for people coming from different programming languages.
Say I have a list:
names = ["Bob", "Billy", "Samuel", "Adam", "Rob"]
This is one way I can check if the list is empty:
is_empty = bool(names)
This is another:
is_empty = any(names)
I do realize the any function checks if there is at least 1 true value inside a list. What would be the best and quickest way to check if the list is empty? Which would look the best and in which scenarios? Are there any faster ways that I do not know of?
It's simplest to just use the implicit boolean method of lists:
if mylist: will branch True if mylist has contents, and False if mylist is empty. From the documentation, an empty list is considered to be False as in boolean evaluation the default __len__() method is called and it is equal to zero. This is the most pythonic and the fastest way to evaluate it, though mechanistically identical to if len(mylist) == 0:. The same applies to strings, tuples, lists, dictionaries, sets, and range().
Edit: With regards to one of the given examples, as noted by @Carcigenicate, any() will fail in select situations if the goal is purely to check if a list is empty. any() will return False "if the list is non-empty and contains only Falsey elements."
For example, any([False, 0]) will return False despite the list containing two objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With