In this example we will discuss 4 different ways to count number of elements in a list that satisfy certain conditions.
Suppose we have a list of numbers i.e.
# List of numbers listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101]
We want to count number of elements in the list that satisfy our given conditions. These conditions can be like,
 Number should be Odd i.e. x % 2 == 1
 Number should be Even i.e. x % 2 == 0
 Number should be greater than five i.e. x > 5
 Number should be greater than five and less than twenty i.e. x > 5 and x < 20
There are different ways to do it. Let’s discuss them one by one,
Use map() & sum() to count elements in a list that satisfy certain conditions
map() function
map(function, iterable, ...)
map() Function in python accepts a function and an iterable like list. Then applies the given function to each element in the list and appends the result of function in a new list. In the end map() returns this new list i.e. list of results.
sum() Function
sum(iterable, start=0)
sum() function adds the items in the given iterable.
Let’s use both of these functions to count elements in a list by condition.
Count odd numbers in the list
Single line solution is,
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Count odd numbers in the list count = sum(map(lambda x : x%2 == 1, listOfElems)) print('Count of odd numbers in a list : ', count)
Output:
Count of odd numbers in a list : 6
How did it worked ?
Let’s break the above solution in small steps to understand how it worked.
In this case our condition is that number should be odd. So, lets create a lambda function that checks this condition i.e.
lambda x : x%2 == 1
Now pass our condition / lambda function to map() and get a map object of results i.e.
mapObj = map(lambda x : x%2 == 1, listOfElems)
The given lambda function is applied to each element in the list and result is stored in the map object. As our lambda function returns a a bool, so map object contains bool elements. We can check the result by printing map object contents i.e.
print('Contents of map object : ', list(mapObj))
Output:
Contents of map object : [True, False, True, True, False, True, False, True, True]
Number of True in this bool list represents the count of odd elements in the list. Let’s count the occurrences of True in this map object using sum() function i.e.
# Add number of True / 1 in the map object of bools count = sum(mapObj)
This is how we found count of elements in list that satisfies a given condition.
Let’s see some more examples to count elements in list based on conditions using sum() & map()
Count even numbers in the list
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Count even numbers in the list count = sum(map(lambda x : x%2 == 0, listOfElems)) print('Count of even numbers in a list : ', count)
Output:
Count of even numbers in a list : 3
Count numbers in a list which are greater than 5
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = sum(map(lambda x : x>5, listOfElems)) print('Count of numbers in a list which are greater than 5: ', count)
Output:
Count of numbers in a list which are greater than 5: 9
Use sum() & Generator expression to count elements in list based on conditions
Let’s create a function that uses sum() & Generator Expression to count number of elements in a list that satisfies our given condition i.e.
def getCount(listOfElems, cond = None): 'Returns the count of elements in list that satisfies the given condition' if cond: count = sum(cond(elem) for elem in listOfElems) else: count = len(listOfElems) return count
This function accepts a list and a callback function as argument. Callback function will be our function that checks the condition. This function calls the given callback function on each element in the list and returns a count of elements in list that returns True when passed to our condition i.e. callback.
Let’s use this function to count number of elements in list that satisfies our condition,
Count numbers in a list which are greater than 5:
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = getCount(listOfElems, lambda x : x>5) print('Count of numbers in a list which are greater than 5: ', count)
Output:
Count of numbers in a list which are greater than 5: 9
Count numbers in a list which are greater than 5 but less than 20:
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 but less than 20 count = getCount(listOfElems, lambda x : x>5 and x < 20) print('Count of numbers in a list which are greater than 5 but less than 20 : ', count)
Output:
Count of numbers in a list which are greater than 5 but less than 20 : 1
If no callback function is passed then this function will return the total number of elements in the list i.e.
Count total number of elements in the list
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # Get total number of elements in the list count = getCount(listOfElems) print('Total Number of elements in List: ', count)
Output
Total Number of elements in List: 9
Use len() & List comprehension to count elements in list based on conditions
We can use list comprehension to create a new list of elements that satisfies our given condition and then get the length of this new list to find out number of elements in original list that satisfies our condition i.e.
Count numbers in a list which are greater than 5
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = len([elem for elem in listOfElems if elem > 5]) print('Count of numbers in a list which are greater than 5: ', count)
Output:
Count of numbers in a list which are greater than 5: 9
Use reduce() function to count elements in list based on conditions
Count of numbers in a list which are greater than 5
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] # count numbers in the list which are greater than 5 count = reduce(lambda default, elem: default + (elem > 5), listOfElems, 0) print('Count of numbers in a list which are greater than 5: ', count)
Output:
Count of numbers in a list which are greater than 5: 9
reduce() function will iterate over the list check condition & add each True values to count number of elements that satisfies the given condition.
Complete example is as follows,
from functools import reduce def getCount(listOfElems, cond = None): 'Returns the count of elements in list that satisfies the given condition' if cond: count = sum(cond(elem) for elem in listOfElems) else: count = len(listOfElems) return count def main(): # List of numbers listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101] print('**** Use map() & sum() to count elements in a list that satisfy certain conditions ****') print('** Example 1 **') # Count odd numbers in the list count = sum(map(lambda x : x%2 == 1, listOfElems)) print('Count of odd numbers in a list : ', count) print('** Example 1 : Explanation **') # Get a map object by applying given lambda to each element in list mapObj = map(lambda x : x%2 == 1, listOfElems) print('Contents of map object : ', list(mapObj)) print('** Example 2**') # Count even numbers in the list count = sum(map(lambda x : x%2 == 0, listOfElems)) print('Count of even numbers in a list : ', count) print('** Example 3**') # count numbers in the list which are greater than 5 count = sum(map(lambda x : x>5, listOfElems)) print('Count of numbers in a list which are greater than 5: ', count) print('**** Using sum() & Generator expression to count elements in list based on conditions ****') # count numbers in the list which are greater than 5 count = getCount(listOfElems, lambda x : x>5) print('Count of numbers in a list which are greater than 5: ', count) # count numbers in the list which are greater than 5 but less than 20 count = getCount(listOfElems, lambda x : x>5 and x < 20) print('Count of numbers in a list which are greater than 5 but less than 20 : ', count) # Get total number of elements in the list count = getCount(listOfElems) print('Total Number of elements in List: ', count) print('**** Use List comprehension to count elements in list based on conditions ****') # count numbers in the list which are greater than 5 count = len([elem for elem in listOfElems if elem > 5]) print('Count of numbers in a list which are greater than 5: ', count) print('**** Use reduce() function to count elements in list based on conditions ****') # count numbers in the list which are greater than 5 count = reduce(lambda default, elem: default + (elem > 5), listOfElems, 0) print('Count of numbers in a list which are greater than 5: ', count) if __name__ == '__main__': main()
Output:
**** Use map() & sum() to count elements in a list that satisfy certain conditions **** ** Example 1 ** Count of odd numbers in a list : 6 ** Example 1 : Explanation ** Contents of map object : [True, False, True, True, False, True, False, True, True] ** Example 2** Count of even numbers in a list : 3 ** Example 3** Count of numbers in a list which are greater than 5: 9 **** Using sum() & Generator expression to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9 Count of numbers in a list which are greater than 5 but less than 20 : 1 Total Number of elements in List: 9 **** Use List comprehension to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9 **** Use reduce() function to count elements in list based on conditions **** Count of numbers in a list which are greater than 5: 9
Pandas Tutorials Learn Data Analysis with Python

Pandas Tutorial Part #1  Introduction to Data Analysis with Python

Pandas Tutorial Part #2  Basics of Pandas Series

Pandas Tutorial Part #3  Get & Set Series values

Pandas Tutorial Part #4  Attributes & methods of Pandas Series

Pandas Tutorial Part #5  Add or Remove Pandas Series elements

Pandas Tutorial Part #6  Introduction to DataFrame

Pandas Tutorial Part #7  DataFrame.loc[]  Select Rows / Columns by Indexing

Pandas Tutorial Part #8  DataFrame.iloc[]  Select Rows / Columns by Label Names

Pandas Tutorial Part #9  Filter DataFrame Rows

Pandas Tutorial Part #10  Add/Remove DataFrame Rows & Columns

Pandas Tutorial Part #11  DataFrame attributes & methods

Pandas Tutorial Part #12  Handling Missing Data or NaN values

Pandas Tutorial Part #13  Iterate over Rows & Columns of DataFrame

Pandas Tutorial Part #14  Sorting DataFrame by Rows or Columns

Pandas Tutorial Part #15  Merging or Concatenating DataFrames

Pandas Tutorial Part #16  DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most soughtafter professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.