Python | Check if all items in the list match the condition



Method # 1: Using all()
We can use all () to accomplish this particular task. In this we pass a condition and the validation of all elements is checked by all () inside.

# Python3 code to demonstrate how it works
# Check if all items in the list match the condition
# Use all ()

 
# initializing list

test_list = [ 4 , 5 , 8 , 9 , 10 ]

 
# print list

print ( "The original list: " + str (test_list))

 
# Check if all items in the list meet the condition
# Use all ()

res = all (ele & gt;  3 for ele in test_list)

 
# Print result

print ( "Are all elements greater than 3?:" + str (res ))

Output:

 The original list: [4, 5, 8, 9, 10] Are all elements greater than 3? : True 

Method # 2: Using itertools.takewhile()
This function can also be used to code a solution this problem. In this, we just need to process the loop until the condition is met and increment the counter. If it matches the length of the list, then all elements meet this condition.

# Python3 code to demonstrate how it works
# Check if all items in the list meet the condition
# Using itertools.takewhile ()

import itertools

 
# initializing list

test_list = [ 4 , 5 , 8 , 9 , 10 ]

 
# print list

print ( "The original list:" + str (test_list))

 
# Check if all items in the list match
# Using itertools.takewhile ()

count = 0

for ele in itertools.takewhile ( lambda x: x & gt;  3 , test_list):

count = count + 1

res = count = = len (test_list)

 
# Print result

print ( "Are all elements greater than 3?: " + str (res))

Output:

 The original list : [4, 5, 8, 9, 10] Are all elements greater than 3? : True