Open In App

Python | Check if all elements in list follow a condition

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can have a problem in which we need to check if all the elements in list abide to a particular condition. This can have application in filtering in web development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using all() We can use all(), to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally. 

Python3




# Python3 code to demonstrate working of
# Check if all elements in list follow a condition
# Using all()
 
# initializing list
test_list = [4, 5, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Check if all elements in list follow a condition
# Using all()
res = all(ele > 3 for ele in test_list)
 
# Printing 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

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

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

Python3




# Python3 code to demonstrate working of
# Check if all elements in list follow a condition
# Using itertools.takewhile()
import itertools
 
# initializing list
test_list = [4, 5, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Check if all elements in list follow a condition
# Using itertools.takewhile()
count = 0
for ele in itertools.takewhile(lambda x: x > 3, test_list):
    count = count + 1
res = count == len(test_list)
 
# Printing 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

Time Complexity: O(n) where n is the number of elements in the list “test_list”. itertools.takewhile() performs n number of operations.
Auxiliary Space: O(1), constant extra space is required 

Method #3:Using lambda functions

Python3




# Python3 code to demonstrate working of
# Check if all elements in list follow a condition
# Using lambda functions
 
# initializing list
test_list = [4, 5, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Check if all elements in list follow a condition
# Using filter
res = list(filter(lambda x: x > 3, test_list))
if(len(res) == len(test_list)):
    res = True
else:
    res = False
# Printing 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

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #4: Using map() and any()

Explanation: Using map() function, we can apply the given condition to each element in the list and return a list of True or False. The any() function will check if any of the element in the returned list is False, which means that not all elements in the original list follow the condition.

Python3




# initializing list
test_list = [4, 5, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Check if all elements in list follow a condition
# Using map() and any()
result = not any(map(lambda x: x <= 3, test_list))
 
# Printing result
print("Are all elements greater than 3 ? : " + str(result))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 5: Using a for loop to iterate over the list and check if each element is greater than 3.

  • Initialize a boolean variable result to True.
  • Iterate over each element x in the list test_list.
  • Check if x is less than or equal to 3, if yes, set result to False and break the loop.
  • Print the result.

Python3




# initializing list
test_list = [4, 5, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Check if all elements in list follow a condition
# Using for loop
result = True
for x in test_list:
    if x <= 3:
        result = False
        break
 
# Printing result
print("Are all elements greater than 3 ? : " + str(result))


Output

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

Time complexity: O(n) as it iterates over each element of the list once. :
Auxiliary space: O(1) as it only uses a boolean variable and a loop variable



Similar Reads

Python | Check whether two lists follow same pattern or not
Given two lists [Tex]A[/Tex] and [Tex]B[/Tex], check if they follow the same pattern or not. Condition for pattern matching: [Tex]Ai[/Tex] &gt; [Tex]Aj[/Tex], then [Tex]Bi[/Tex] &gt; [Tex]Bj[/Tex] [Tex]Ai[/Tex] = [Tex]Aj[/Tex], then [Tex]Bi[/Tex] = [Tex]Bj[/Tex] [Tex]Ai[/Tex] &lt; [Tex]Aj[/Tex], then [Tex]Bi[/Tex] &lt; [Tex]Bj[/Tex], for all i, j.
2 min read
Python | Check if any element in list satisfies a condition
Sometimes, while working with Python lists, we can have a problem to filter a list. One of the criteria of performing this filter operation can be checking if any element exists in list that satisfies a condition. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension This problem can be easily solved u
5 min read
Remove Elements From a List Based on Condition in Python
In Python, lists are a versatile and widely used data structure. There are often situations where you need to remove elements from a list based on a specific condition. In this article, we will explore five simple and commonly used methods to achieve this task. Remove Elements From A List Based On A Condition In PythonBelow, are the methods of Remo
3 min read
Python program to find all the Combinations in the list with the given condition
Given a list with some elements being a list of optional elements. The task is to find all the possible combinations from all options. Examples: Input: test_list = [1,2,3] Output: [1], [1, 2], [1, 2, 3], [1, 3] [2], [2, 3], [3] Example 1: Get all possible combinations of a list’s elements using combinations C/C++ Code from itertools import combinat
3 min read
Python - Frequency of x follow y in Number
Sometimes, while working with Numbers in Python, we can have a problem in which we need to get the number of time one number follows other. This can have application in many domains such as day-day programming and other domains. Let us discuss certain ways in which this task can be performed. Method #1: Using loop This is the brute force way in whi
8 min read
How To Follow Links With Python Scrapy ?
In this article, we will use Scrapy, for scraping data, presenting on linked webpages, and, collecting the same. We will scrape data from the website 'https://quotes.toscrape.com/'. Creating a Scrapy Project Scrapy comes with an efficient command-line tool, also called the 'Scrapy tool'. Commands are used for different purposes and, accept a differ
9 min read
Check if elements of an array can be arranged satisfying the given condition
Given an array arr of N (even) integer elements. The task is to check if it is possible to reorder the elements of the array such that: arr[2*i + 1] = 2 * A[2 * i] for i = 0 ... N-1. Print True if it is possible, otherwise print False. Examples: Input: arr[] = {4, -2, 2, -4} Output: True {-2, -4, 2, 4} is a valid arrangement, -2 * 2 = -4 and 2 * 2
5 min read
Python | Remove first K elements matching some condition
Removal of elements in list can be performed using many inbuilt functions. Removing all or just a single occurrence removal both functions are present in Python library. This article discusses to remove just the first K occurrences of elements matching particular condition. Method #1: Naive Method We can append the elements that are matching condit
3 min read
Python | Count of elements matching particular condition
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved. Method #1 : Using sum() + generato
5 min read
Python - Sum elements matching condition
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals sum that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved. Method #1 : Using loop This is
3 min read
Practice Tags :