R Basic

How to Check If a List is Empty in R

What do we mean when we say an empty list? An empty list does not contain elements. It exists in the memory but does not have any elements stored in it.

The efficient way to check if a list is empty in R is by comparing its length with 0. If it returns TRUE, that means the list is empty; otherwise not.

You can check the length of any input object using the length() function.

 

Syntax

length(main_list) == 0

Example

You can create an empty list by using the list() function, which does not accept any arguments.

main_list <- list()

print(length(main_list) == 0) # TRUE

As expected, it returns TRUE since the input list is empty.

Let’s take another scenario where the list is not empty.

main_list <- list(c(19, 21), c("KB", "KL"))

print(length(main_list) == 0) # FALSE

As expected, it returns FALSE since the input list object is not empty anymore.

Shorter way to check

You can use the shorter syntax “!length()”.

main_list <- list()

print(!length(main_list)) # TRUE

And for non-empty lists:

main_list <- list(c(19, 21), c("KB", "KL"))

print(!length(main_list)) # FALSE

That’s all!

Recent Posts

What is is.factor() Function in R

R consists of various data types, and "factor" is one of them. You can use…

9 hours ago

Efficiently Check If a Vector is Empty in R

The most efficient and idiomatic way to check if a vector is empty in R…

1 day ago

Checking If a Data Frame is Empty in R

What criteria are being evaluated to determine if a data frame is empty? There is…

2 days ago

is.element() Function: Check Presence of Elements in R

Whether you want to do membership testing, filter data, identify missing values, check for duplicates,…

4 days ago

as.double() and is.double() Functions in R Language

Whether you want to perform calculations efficiently or derive accurate analysis, you need a double-precision…

1 week ago

What is is.complex() function in R

If you are working with imaginary components, you might want to find whether you are…

1 week ago