Pythonic Way of Checking If a Condition Holds for Any Element of a List

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
# do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

How to check if all elements of a list match a condition?

The best answer here is to use all(), which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:

>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False

Note that all(flag == 0 for (_, _, flag) in items) is directly equivalent to all(item[2] == 0 for item in items), it's just a little nicer to read in this case.

And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):

>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]

If you want to check at least one element is 0, the better option is to use any() which is more readable:

>>> any(flag == 0 for (_, _, flag) in items)
True

Check whether a condition is True for any element of a list (OR operation)

You can do that with any (which short circuits). As an additional optimization, you can zip your list with itself shifted by 1, then compare.

def has_same_adjecent(data):
return any(x == y for x, y in zip(data, data[1:]))

has_same_adjecent([3, 1, 3, 3])
# True

Is there a Python function that checks if any list element is of a specific data type?

There are many ways to apply something to entire container, e.g.

any(isinstance(element, complex) for element in container)

checking if all elements in a list satisfy a condition

Expanding Green Cloak Guy answer, with addition of break

for path in Path(spath).iterdir():
for n in cosine_sim(file, path):
if all(int(x) < 95 for x in n):
print("suceess...")
break
break

two break because there are two loops...

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-booleans in the iterable will be fine — bool(x) will map (or coerce, if you prefer) any x according to these rules:

  • 0, 0.0, None, [], (), [], set(), and other empty collections are mapped to False
  • anything else is 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

Check a condition on a list and find exactly the number of elements that violate the condition

In [1]: A = [[-1 - 2*1j, -1 + 2*1j], [-5, -4], [7 - 9*1j, 7 + 9*1j], [9]]
In [2]: violates = [i for i, a in enumerate(A) if any([aa.real > 0 for aa in a])]
In [3]: violates
Out[3]: [2, 3]

idiomatic way for checking all N'th idx elements in list

any will look for the first entry for which the condition is True (and therefore not necessarily iterate over your whole list):

any(y is not None for x_, y in ls)

Check if a list contains any list

Try using any:

print(any(isinstance(i, list) for i in b))


Related Topics



Leave a reply



Submit