Python | Count of elements matching particular condition
Last Updated :
12 Apr, 2023
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() + generator expression This method uses the trick of adding 1 to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of count of numbers matching a condition is returned.
Python3
# Python 3 code to demonstrate
# to get count of elements matching condition
# using sum() + generator expression
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using sum() + generator expression
# to get count of elements matching condition
# checks for odd
res = sum(1 for i in test_list if i % 2 != 0)
# printing result
print ("The number of odd elements: " + str(res))
Output :
The original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Method #2 : Using sum() + map() map() does the task almost similar to the generator expression, difference is just the internal data structure employed by it is different hence more efficient.
Python3
# Python 3 code to demonstrate
# to get count of elements matching condition
# using sum()+ map()
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using sum()+ map()
# to get count of elements matching condition
# checks for odd
res = sum(map(lambda i: i % 2 != 0, test_list))
# printing result
print ("The number of odd elements: " + str(res))
Output :
The original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Time Complexity: O(n), where n is length of test_list.
Auxiliary Space: O(1)
Method #3 : Using reduce() + lambda reduce function does the task of accumulation as the sum function in the above used methods. lambda is used to perform the condition against which result needs to be checked.
Python3
# Python 3 code to demonstrate
# to get count of elements matching condition
# using reduce() + lambda
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using reduce() + lambda
# to get count of elements matching condition
# checks for odd
res = reduce(lambda count, i: count + (i % 2 != 0), test_list, 0)
# printing result
print ("The number of odd elements: " + str(res))
Output :
The original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Method #4: Using filter()+len()+list()+lambda functions
Python3
# Python 3 code to demonstrate
# to get count of elements matching condition
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
res = len(list(filter(lambda x: x % 2 != 0, test_list)))
# printing result
print("The number of odd elements: " + str(res))
OutputThe original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #5 : Using the collections.Counter class:
Use the Counter class to count the number of elements matching the condition
Python3
from collections import Counter
# initialize the list
test_list = [3, 5, 1, 6, 7, 9]
# print the original list
print("The original list is :", test_list)
# use the Counter class to count the number of elements matching the condition
# the condition here is i % 2 != 0, which checks for odd numbers
# the Counter class returns a dictionary with the counts of each element
counts = Counter(i % 2 != 0 for i in test_list)
# print the count of odd elements
# the count of odd elements is stored as the value for the key True in the counts dictionary
print("The number of odd elements:", counts[True])
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Time complexity: O(N)
Auxiliary space: O(N)
Method #6 : Using a for loop
Python3
test_list = [3, 5, 1, 6, 7, 9]
res = 0
# printing original list
print ("The original list is : " + str(test_list))
for i in test_list:
if i % 2 != 0:
res += 1
print ("The number of odd elements: " + str(res))
#This code is contributed by Jyothi pinjala.
OutputThe original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5
Time complexity: O(N)
Auxiliary space: O(1)
Similar Reads
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Python - Find all elements count in list
In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
3 min read
Python Counter | Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: Examples: Input : 3 3 4
2 min read
Count occurrences of an element in a list in Python
A common task when working with lists is to count how many times a specific element appears. In Python, we have several ways to count occurrences of an element using both built-in and custom methods.The simplest and most straightforward way to count occurrences of an element in a list is by using th
2 min read
Python | Count occurrences of an element in a Tuple
In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using a simple approach and how inbuilt functions can be used to solve this problem. Examples: Tuple:
3 min read
Count the Number of Null Elements in a List in Python
In data analysis and data processing, It's important to know about Counting the Number of Null Elements. In this article, we'll explore how to count null elements in a list in Python, along with three simple examples to illustrate the concept. Count the Number of Null Elements in a List in PythonIn
3 min read
Python | Count the Number of matching characters in a pair of string
The problem is about finding how many characters are the same in two strings. We compare the strings and count the common characters between them. In this article, we'll look at different ways to solve this problem.Using Set Sets are collections of unique items, so by converting both strings into se
2 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read
Count rows based on condition in Pyspark Dataframe
In this article, we will discuss how to count rows based on conditions in Pyspark dataframe. For this, we are going to use these methods: Using where() function.Using filter() function. Creating Dataframe for demonstration: Python3 # importing module import pyspark # importing sparksession from pysp
4 min read
How to parse XML and count instances of a particular node attribute in Python?
In this article, we will see how to parse XML and count instances of a particular node attribute in Python. What is XML? Extensible Markup Language (XML) Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable a
3 min read