How to Test If List Element Exists

How to test if list element exists?

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

If list index exists, do X

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?

Fastest way to check if a value exists in a list


7 in a

Clearest and fastest way to do it.

You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)

How can I check if a list index exists?

You just have to check if the index you want is in the range of 0 and the length of the list, like this

if 0 <= index < len(list):

it is actually internally evaluated as

if (0 <= index) and (index < len(list)):

So, that condition checks if the index is within the range [0, length of list).

Note: Python supports negative indexing. Quoting Python documentation,

If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

It means that whenever you use negative indexing, the value will be added to the length of the list and the result will be used. So, list[-1] would be giving you the element list[-1 + len(list)].

So, if you want to allow negative indexes, then you can simply check if the index doesn't exceed the length of the list, like this

if index < len(list):

Another way to do this is, excepting IndexError, like this

a = []
try:
a[0]
except IndexError:
return False
return True

When you are trying to access an element at an invalid index, an IndexError is raised. So, this method works.


Note: The method you mentioned in the question has a problem.

if not mylist[1]:

Lets say 1 is a valid index for mylist, and if it returns a Falsy value. Then not will negate it so the if condition would be evaluated to be Truthy. So, it will return False, even though an element actually present in the list.

Check if element exist in list

We can avoid loops altogether and instead use a list comprehension:

ipaddress = [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']]
newipaddress = [["10.110.34.50"], ["10.25.17.212"], ["10.90.90.10"]]
output = [x in newipaddress for x in ipaddress]
print(output) # [False, False, False, True]

To display the element in the first list, if it exist in the second list, use:

output = [x for x in ipaddress if x in newipaddress]
print(output) # [['10.90.90.10']]

Check if a list element exists in a string

any() produces True or False, and the generator expression variables are not available outside of the expression:

>>> l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']
>>> s = 'YTG'
>>> any(i in s for i in l)
True
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined

Use a list comprehension to list all matching letters:

matching = [i for i in l if i in s]
if matching:
print matching

That preserves the order in l; if the order in matching doesn't matter, you could just use set intersections. I'd make l a set here:

l = set(['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M'])  # Python 3 can use {...}
matching = l.intersection(s)
if matching:
print matching

By making l the set, Python can iterate over the shorter s string.

Check if a List Element Exists in Dictionary Values

You can use a dict comprehension:

>>> {k: v for k, v in dict0.items() if v in list0}
{91: -0.1037212327115436, 115: -0.2307061452151448, 266: -0.09614853460521154, 290: -0.2138622652947372, 347: 9.353161396230564e-07, 441: -0.1072424768342444, 465: -0.2385384148158066, 606: -0.1098235264547504, 771: -0.0966926943378552, 794: -0.2150726345799602}

If your list0 is very big, converting it to a set makes the above method faster:

>>> set0 = set(list0)
>>> {k: v for k, v in dict0.items() if v in set0}

check if list element exists in an R list

It works for me:

ans <- list(c("<dd>male, 31 years old</dd>", "black male", "31"  ), character(0))
count <- 0
age <- "31"
for(item in ans){
if (isTRUE(item[3] == age)) {
count <- count + 1
}
}
count

Is this what you want?



Related Topics



Leave a reply



Submit