In this article, we will learn how to check if all elements of a list matches a given condition in Python.
Table Of Contents
Solution 1 : Using all() function
To verify if all elements in a list matches a condition, apply the given condition to each element of list and store results in a boolean list. Size of this boolean list will be equal to the size of the original list. Also, a True value in this boolean list tells that the corresponding value in original list matches the condition. So, if all elements in this boolean list are True, then it means all elements in original list matches the given condition. Now to check if all elements of a list are True, we can use the all() function. It accepts a sequence of boolean type elements and returns True if all the elements in that sequence evaluates to True.
Let’s see an example, where we will check if all the numbers in list are odd or not.
# Check if a Number is Odd def IsOdd(num): result = False if num % 2 == 1: result = True return result listOfNumbers = [67, 79, 55, 43, 91, 99, 77] # Check if all elements of a list matches a condition # i.e. all elements are Odd if all(IsOdd(num) for num in listOfNumbers): print('Yes, all elements in List matches the condition') else: print('No, all elements in List do not matches the condition')
Output
Yes, all elements in List matches the condition
Here, we confirmed that all elements in the list are True.
Solution 2 : Using for-loop
Iterate over all elements of a list using a for loop and apply the given condition on each element. For any element, if the given condition evaluates to False, then it means all the elements of the list does not matches the given condition. If all evaluates to True, then it means all the elements of the list matches the given condition.
Frequently Asked:
- Python : How to add an element in list ? | append() vs extend()
- Convert a comma-separated string to a List in Python
- Convert a list to a comma-separated string in Python
- Convert a List of Tuples to a List in Python
Let’s see an example, where we will check if all the numbers in list are odd or not.
# Check if a Number is Odd def IsOdd(num): result = False if num % 2 == 1: result = True return result listOfNumbers = [67, 79, 55, 43, 91, 99, 77] result = True # Check if all elements of a list matches a condition # i.e. all elements are Odd for num in listOfNumbers: if IsOdd(num) == False: result = False break if result: print('Yes, all elements in List matches the condition') else: print('No, all elements in List do not matches the condition')
Output
Yes, all elements in List matches the condition
Here, we confirmed that all elements in the list are True.
Summary
We learned different ways to check if all elements of a list satisfies a given condition or not. Thanks.