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.
length(main_list) == 0
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.
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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
The scale() function in R centers (subtracting the mean) and/or scales (dividing by the standard…
To rename a file in R, you can use the file.rename() function. It renames a…
The prop.table() function in R calculates the proportion or relative frequency of values in a…
The exp() is a built-in function that calculates the exponential of its input, raising Euler's…
The split() function divides the input data into groups based on some criteria, typically specified…
The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…