VOOZH about

URL: https://www.geeksforgeeks.org/python/python-count-of-elements-matching-particular-condition/

⇱ Python | Count of elements matching particular condition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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. 
 

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. 
 

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. 
 

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


Output
The 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
 


Output
The 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


Output
The original list is : [3, 5, 1, 6, 7, 9]
The number of odd elements: 5

Time complexity: O(N)
Auxiliary space: O(1)

Comment
Article Tags: