How to test if list element exists?

python check if value exists in list
check if value is in list python
python check if list contains elements of another list
how to check if a word is in a list python
how to check if a number is in a list python
fastest way to check if a value exists in a list python
test value in list
python list contains string
Problem

I would like to test if an element of a list exists, here is an example

foo <- list(a=1)
exists('foo') 
TRUE   #foo does exist
exists('foo$a') 
FALSE  #suggests that foo$a does not exist
foo$a
[1] 1  #but it does exist

In this example, I know that foo$a exists, but the test returns FALSE.

I looked in ?exists and have found that with(foo, exists('a') returns TRUE, but do not understand why exists('foo$a') returns FALSE.

Questions
  • Why does exists('foo$a') return FALSE?
  • Is use of with(...) the preferred approach?

This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a). A more stringent test might be to check that the name is actually defined in the list:

foo <- list(a=42, b=NULL)
foo

is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE

"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE

...and foo[["a"]] is safer than foo$a, since the latter uses partial matching and thus might also match a longer name:

x <- list(abc=4)
x$a  # 4, since it partially matches abc
x[["a"]] # NULL, no match

[UPDATE] So, back to the question why exists('foo$a') doesn't work. The exists function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a" is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE...

foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42   # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a" 
exists("foo$a") # FALSE 
exists("bar$a") # TRUE

Python : How to Check if an item exists in list ?, Check if element exist in list based on custom logic. Python any() function checks if any Element of given Iterable is True. Let's use it to check if  This article discusses one of the basic list operation of ways to check existence of element in list. Method 1 : Naive Method. In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list.


The best way to check for named elements is to use exist(), however the above answers are not using the function properly. You need to use the where argument to check for the variable within the list.

foo <- list(a=42, b=NULL)

exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE

Python, Python | Ways to check if element exists in list. List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of  In this example we are using ‘in’ operator to check if item or element exists in the list. If an item or element exists in the list, it will return the output as true, else false.


A slight modified version of @salient.salamander , if one wants to check on full path, this can be used.

Element_Exists_Check = function( full_index_path ){
  tryCatch({
    len_element = length(full_index_path)
    exists_indicator = ifelse(len_element > 0, T, F)
      return(exists_indicator)
  }, error = function(e) {
    return(F)
  })
}

How to test if list element exists?, The exists function will only check if a variable exists in an environment, not if the parts of an object exist. The string "foo$a" is interpreted  Check if an element exists in the list using any() Using Python any() function is the most classical way in which you can perform this task and also efficiently. The any() function checks for a match in a string with a match of each element of the list.


Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Java ArrayList contains() - Check if element exists, If the index is greater than '0' than element is present in the list. contains() method​. public boolean contains(Object o) {. ArrayList contains() method is used to check if the specified element exists in the given arraylist or not. If element exist then method returns true, else false. 1. ArrayList contains() syntax. The contains() method is pretty simple. It simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.


One solution that hasn't come up yet is using length, which successfully handles NULL. As far as I can tell, all values except NULL have a length greater than 0.

x <- list(4, -1, NULL, NA, Inf, -Inf, NaN, T, x = 0, y = "", z = c(1,2,3))
lapply(x, function(el) print(length(el)))
[1] 1
[1] 1
[1] 0
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 3

Thus we could make a simple function that works with both named and numbered indices:

element.exists <- function(var, element)
{
  tryCatch({
    if(length(var[[element]]) > -1)
      return(T)
  }, error = function(e) {
    return(F)
  })
}

If the element doesn't exist, it causes an out-of-bounds condition caught by the tryCatch block.

Python: Check if Element Exists in List, If an item exists in the list, it will return the output is true, else it returns false. Example: # Python3 code # Check if element exists in the list # Using  Check if element exist in list based on custom logic. Python any() function checks if any Element of given Iterable is True. Let’s use it to check if any string element in list is of length 5 i.e.


Python List Contains, Python list is an essential container as if stores elements of all the datatypes as a​  List<T>.Contains(T) Method is used to check whether an element is in the List<T> or not. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements.


Python : How to check if list contains value, In this quick code reference, I will demonstrate how to check whether value or item exists in python list or not. It is very easy to find if list contains  Set a list − List < string > list1 = new List < string > { Lawrence, Adams, Pitt, Tom }; Now use the Contains method to check if an i


Check if list contains a value, in Haskell, For empty list false. If first element match true. Check rest of the elements recursively. Ada; C; Caml; Clojure; Clojure; C++; C++; C#; D; Dart; Elixir; Elixir; Erlang  The Find, FindLast, and FindAll methods are used to search the list with the search predicate method, and then the RemoveAll method is used to remove all entries ending with "saurus". Finally, the Exists method is called. It traverses the list from the beginning, passing each element in turn to the EndsWithSaurus method.