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

cbind() Function: Binding R Objects by Columns

R cbind (column bind) is a function that combines specified vectors, matrices, or data frames…

20 hours ago

rbind() Function: Binding Rows in R

The rbind() function combines R objects, such as vectors, matrices, or data frames, by rows.…

1 day ago

as.numeric(): Converting to Numeric Values in R

The as.numeric() function in R converts valid non-numeric data into numeric data. What do I…

1 week ago

Calculating Natural Log using log() Function in R

The log() function calculates the natural logarithm (base e) of a numeric vector. By default,…

2 weeks ago

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of…

4 weeks ago

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only…

1 month ago