How do I check if a list is empty?
if not a:
print("List is empty")
Using the implicit booleanness of the empty list
is quite pythonic.
What is the quickest way to check if a list is empty, and in what scenarios would one method be preferred over the other?
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.
How to check if a list is empty
You can use a function that recursively checks the items within sublists:
def is_empty(l):
return all(is_empty(i) if isinstance(i, list) else False for i in l)
so that:
print(is_empty([[], [], [[], []]]))
print(is_empty([[], [], [[], [1]]]))
outputs:
True
False
And if you want to handle lists that contain circular references you can use a seen
set to keep track of the list references the function has seen and skip them when they are seen:
def is_empty(l, seen=None):
if seen is None:
seen = set()
return all(seen.add(id(i)) or is_empty(i, seen) if isinstance(i, list) else False for i in l if id(i) not in seen)
so that:
a = []
a.append(a)
print(is_empty(a))
a = [1]
a.append(a)
print(is_empty(a))
outputs:
True
False
How to check if a list is empty in Python?
if not myList:
print "Nothing here"
Python: condition to check that none of list's element is an empty list
Since an non-empty list is considered truthy, you can use all
:
if all(A):
print("No empty list in A")
else:
print("At least one empty list in A")
How to check if a list has both empty and non-empty values in python
list = ["Efsf","efsfs",""]
list1 = ["",'']
list2 = ["fsef",5 ,5]
def check(list):
null =''
if null in list and len(list)-list.count(null)>0:
print("List has both empty and non-empty values.")
else:
print("List does not have both empty and non-empty values.")
check(list)
check(list1)
check(list2)
output:
List has both empty and non-empty values.
List does not have both empty and non-empty values.
List does not have both empty and non-empty values.
Two ways to check if a list is empty - differences?
The first tells you whether the list
variable has been assigned a List instance or not.
The second tells you if the List referenced by the list
variable is empty.
If list
is null, the second line will throw a NullPointerException
.
If you want to so something only when the list is empty, it is safer to write :
if (list != null && list.isEmpty()) { do something }
If you want to do something if the list is either null or empty, you can write :
if (list == null || list.isEmpty()) { do something }
If you want to do something if the list is not empty, you can write :
if (list != null && !list.isEmpty()) { do something }
Checking for empty or null List<string>
Try the following code:
if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}
A late EDIT because for these checks I now like to use the following solution.
First, add a small reusable extension method called Safe():
public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}
foreach (var item in source)
{
yield return item;
}
}
}
And then, you can do the same like:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.
And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):
if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}
How check if the lists in a list are not empty?
You can use stream API for this, but also a plain loop too:
boolean allNonEmptyOrNull = myList.stream()
.allMatch(x -> x != null && !x.isEmpty());
Or you can check if null
is contained or an an empty List
for example, via:
System.out.println(myList.contains(null) || myList.contains(Collections.<Integer> emptyList()));
But this last option will break with Java 9 immutable collections, for example:
List.of(1, 2, 3).contains(null);
will throw a NullPointerException
.
Related Topics
Tkinter - Executing Functions Over Time
How to Create a Tuple With Only One Element
How to Print a Single Backslash
How to Resize an Image Using Pil and Maintain Its Aspect Ratio
How to Calculate Number of Days Between Two Given Dates
About the Changing Id of an Immutable String
Using Both Python 2.X and Python 3.X in Ipython Notebook
Split a String by a Delimiter in Python
How to Sort a List of Objects Based on an Attribute of the Objects
How to Add a New Column to an Existing Dataframe
How to Find the Cumulative Sum of Numbers in a List
What Does the "At" (@) Symbol Do in Python
List Comprehension on a Nested List