Test if element is in a list and return 0 or 1
We can try %in%
as.integer(names %in% T1_temp)
Or match
+(!is.na(match(names,T1_temp)))
Python - any() - Check if elements in list is
You are filtering the input list, then asking any()
to test the filtered values. For [0]
, the filtered sequence is still [0]
(albeit as a generated sequence, not an actual list), and you are asking if any of those values are true. 0
is a false value, so any()
returns false:
>>> a = [0]
>>> genexpr = (i for i in a if i >= 0)
>>> list(genexpr)
[0]
>>> bool(0)
False
>>> any(i for i in a if i >= 0)
False
Put the test at the front of the generator expression:
any(i >= 0 for i in a)
That expression doesn't filter, it instead produces a sequence of boolean values, False
if the test doesn't pass, True
if it does. For [0]
, that produces the sequence with a single True
value, so any()
returns True
:
>>> genexpr = (i >= 0 for i in a)
>>> list(genexpr)
[True]
>>> any(i >= 0 for i in a)
True
Check if all values in list are greater than a certain number
Use the all()
function with a generator expression:
>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False
Note that this tests for greater than or equal to 30, otherwise my_list1
would not pass the test either.
If you wanted to do this in a function, you'd use:
def all_30_or_up(ls):
for i in ls:
if i < 30:
return False
return True
e.g. as soon as you find a value that proves that there is a value below 30, you return False
, and return True
if you found no evidence to the contrary.
Similarly, you can use the any()
function to test if at least 1 value matches the condition.
Check if there are values other than a certain value exists in a list
Just use any
, it is designed exactly for what you want:
In [1]: l = [0, 1, 2]
In [2]: any(l)
Out[2]: True
In [4]: l = []
In [5]: any(l)
Out[5]: False
In [6]: l = [0,0,0]
In [7]: any(l)
Out[7]: False
If any value is non-zero it will short circuit and return True, if it gets to the end of the list or you pass an empty list it will return False.
So in your code:
if any(some_list):
# found at least one non-zero
else:
# empty or all zero
If you wanted to check that there was a number greater 1 you would add some logic in the expression:
if any(i > 1 for i in some_list)
The implementation logic is in the linked docs:
def any(iterable):
for element in iterable:
if element:
return True
return False
One thing to be aware of is any will return True for any truthy value like a non-empty list, tuple, True etc.. and False for any falsey values like an empty list, tuple, False etc.. so in certain cases you would need to explicitly check.
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)
Check if any item in Python list is None (but include zero)
For list
objects can simply use a membership test:
None in list_1
Like any()
, the membership test on a list
will scan all elements but short-circuit by returning as soon as a match is found.
any()
returns True
or False
, never None
, so your any(list_1) is None
test is certainly not going anywhere. You'd have to pass in a generator expression for any()
to iterate over, instead:
any(elem is None for elem in list_1)
How to check if one of the following items is in a list?
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
Both empty lists and empty sets are False, so you can use the value directly as a truth value.
Python - Check if element is in 1 or more nested lists and return whole list if TRUE
Here is a rough way to do it:
lists = [
["banana", 10, "yellow"],
["apple", 12, "red"],
["pear", 60, "green"],
["mango", 5, "yellow"],
]
keyword = 'banana'
for lst in lists:
if keyword in lst:
print(lst)
keyword = 'yellow'
for lst in lists:
if keyword in lst:
print(lst)
Ideally you would extract the search to a function accepting the lists and the keyword:
def get_sublists_containing_keyword(lists, keyword):
sublists = []
for lst in lists:
if keyword in lst:
sublists.append(lst)
return sublists
lists = [
["banana", 10, "yellow"],
["apple", 12, "red"],
["pear", 60, "green"],
["mango", 5, "yellow"],
]
banana_lists = get_sublists_containing_keyword(lists, 'banana')
yellow_lists = get_sublists_containing_keyword(lists, 'yellow')
for banana_list in banana_lists:
print(banana_list)
for yellow_list in yellow_lists:
print(yellow_list)
Using any() and all() to check if a list contains one set of values or another
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
- in the case of
all
, no values in the iterable are falsy; - in the case of
any
, at least one value is truthy.
A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-boolean elements in the iterable are perfectly acceptable — bool(x)
maps, or coerces, any x
according to these rules:
0
,0.0
,None
,[]
,()
,[]
,set()
, and other empty collections are mapped toFalse
- all other values are mapped to
True
.
The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You’ve slightly misunderstood how these functions work. The following does something completely different from what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator or a generator expression (≈ lazily evaluated/generated list), or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to the value held by big_foobar
, and (lazily) emits the resulting boolean into the resulting sequence of booleans:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
Related Topics
In Place Modification of Matrices in R
Ggplot2: Have Common Facet Bar in Outer Facet Panel in 3-Way Plot
Error in As.Double(Y):Cannot Coerce Type 'S4' to Vector of Type 'Double'
Copy-On-Modify Semantic on a Vector Does Not Append in a Loop. Why
Extra Curly Braces When Using Xtable and Knitr, After Specifiying Size
Drop Columns That Take Less Than N Values
R: Ggplot2 Setting the Last Plot in the Midle with Facet_Wrap
Recode Multiple Columns Using Dplyr
Efficient Way to Fill Time-Series Per Group
R Packages Fail to Compile with Gcc
How to Shift X Axis Positions of Two Geoms Relative to Each Other
Change Value to Percentage of Row in R
Do I Need to Reshape This Wide Data to Effectively Use Ggplot2
As.Date Produces Unexpected Result in a Sequence of Week-Based Dates