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
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...
The best way to check if all elements of a list matches a condition in for loop?
If you want to have an if
and an else
, you can still use the any
method:
if any(item[2] == 0 for item in items):
print('There is an item with item[2] == 0')
else:
print('There is no item with item[2] == 0')
The any
comes from this answer.
how to check if all elements of java collection match some condition?
If you have java 8, use stream's allMatch
function (reference):
ArrayList<Integer> col = ...;
col.stream().allMatch(i -> i>0); //for example all integers bigger than zero
What’s the best way to check if a list contains an item other than specified item?
With Stream IPA you can achieve that by using terminal operation allMath()
that takes a predicate (function represented by boolean condition) and checks whether all elements in the stream match with the given predicate.
The code will look like that:
public static void main(String[] args) {
List<String> items1 = List.of("apple", "apple", "apple"); // expected true
List<String> items2 = List.of("apple", "orange"); // expected false
System.out.println(items1.stream().allMatch(item -> item.equals("apple")));
System.out.println(items2.stream().allMatch(item -> item.equals("apple")));
}
output
true
false
Check if all elements in a list are identical
Use itertools.groupby
(see the itertools
recipes):
from itertools import groupby
def all_equal(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)
or without groupby
:
def all_equal(iterator):
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == x for x in iterator)
There are a number of alternative one-liners you might consider:
Converting the input to a set and checking that it only has one or zero (in case the input is empty) items
def all_equal2(iterator):
return len(set(iterator)) <= 1Comparing against the input list without the first item
def all_equal3(lst):
return lst[:-1] == lst[1:]Counting how many times the first item appears in the list
def all_equal_ivo(lst):
return not lst or lst.count(lst[0]) == len(lst)Comparing against a list of the first element repeated
def all_equal_6502(lst):
return not lst or [lst[0]]*len(lst) == lst
But they have some downsides, namely:
all_equal
andall_equal2
can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.all_equal
andall_equal3
stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer isFalse
just by looking at the first two elements.- In
all_equal2
the content must be hashable. A list of lists will raise aTypeError
for example. all_equal2
(in the worst case) andall_equal_6502
create a copy of the list, meaning you need to use double the memory.
On Python 3.9, using perfplot
, we get these timings (lower Runtime [s]
is better):
Python - How to check if next few elements in list meet some statement
You can do it like this:
for i in range(len(lst)):
if lst[i] == someValue and all(x != someValue for x in lst[i+1:i+11]):
doSomething()
I changed the variable name from list
to lst
because you shopuld not overwrite the list
builtin type and I also removed the 0
in the range
fucntion as it is not needed.
The all
fucntion checks that every element in the iterable passed as argument evaluates to True
, and our iterable is a sequence of bools with the next 10 elements checked against someValue
.
Another option would be using enumerate(...)
to avoid having to get the value again from the list instead of range(len(...))
:
for i, value in enumerate(lst):
if value == someValue and all(x != someValue for x in lst[i+1:i+11]):
doSomething()
And we could make it into a generator:
for i in (i for i, value in enumerate(lst) if value == someValue and all(x != someValue for x in lst[i+1:i+11])):
doSomething()
@HeapOverflow suggested another way to check for that condition which is more readable (see his answer for further detail and drop a like) that conbined with the generator syntax would be:
for i in (i for i, value in enumerate(lst) if value == someValue not in lst[i+1:i+11]):
doSomething()
How to find first elements in list that match a condition?
The itertools.takewhile
function seems like what you want:
from itertools import takewhile
list(takewhile(lambda x: x % 5 == 0, [5, 10, 15, 16, 20]))
This returns [5, 10, 15]
.
Can i check if condition is true for all elements in a list on Kotlin?
Not sure if you want to check if the condition is true for ALL the elements, or you just want to know which ONE in particular is true, or if ANY are true.
In the first scenario, where we want to know if ALL of them
val list = (1..20).toList() //a bit easier to create the list this way
val result = list.all { control % it == 0 }
println(result) //will print true if all of the elements are true, and false if at least one is false
The second scenario we can do a simple .map, to know each one individually.
val list = (1..20).toList()
val result = list.map { control % it == 0 }
println(result) //will print a list of type (true, false, true, etc) depending on each element
And if we want to check if ANY are true, we can do:
val list = (1..20).toList()
val result = list.any { control % it == 0 }
println(result) //will print true if any of the elements are true, and false if all of the elements are false
Edit since Todd mentioned none
in the comments, I'll add a few other similar functions in case it would help others with similar questions.
Firstly, we don't actually need a list, all of these funcitons can work on the range directly (the ones above and the ones below)
val result = (1..20).all { it % 2 == 0 }
Other similar functions:
none
- the opposite of all
.
filter
- will keep all elements for which the predicate is true.
filterNot
- will keep all elements for which the predicate is false.
Related Topics
Why am I Seeing "Typeerror: String Indices Must Be Integers"
How to Hide Console Window in Python
Using Os.Walk() to Recursively Traverse Directories in Python
How to Save a New Sheet in an Existing Excel File, Using Pandas
How to Capitalize the First Letter of Each Word in a String
Getting Distance Between Two Points Based on Latitude/Longitude
Error After Upgrading Pip: Cannot Import Name 'Main'
Importerror: Dll Load Failed: the Specified Module Could Not Be Found
Python Append() VS. + Operator on Lists, Why Do These Give Different Results
How to Find an Element That Contains Specific Text in Selenium Webdriver (Python)
Random.Seed(): What Does It Do
How to Pass Variables Across Functions
Non-Alphanumeric List Order from Os.Listdir()
How to Jump to a Particular Line in a Huge Text File
How Would You Make a Comma-Separated String from a List of Strings
Update Value of a Nested Dictionary of Varying Depth
What Are the Differences Between the Threading and Multiprocessing Modules