sum(x.b == 1 for x in L)
A boolean (as resulting from comparisons such as x.b == 1) is also an int, with a value of 0 for False, 1 for True, so arithmetic such as summation works just fine.
This is the simplest code, but perhaps not the speediest (only timeit can tell you for sure;-). Consider (simplified case to fit well on command lines, but equivalent):
$ py26 -mtimeit -s'L=[1,2,1,3,1]*100' 'len([x for x in L if x==1])' 10000 loops, best of 3: 56.6 usec per loop $ py26 -mtimeit -s'L=[1,2,1,3,1]*100' 'sum(x==1 for x in L)' 10000 loops, best of 3: 87.7 usec per loopSo, for this case, the "memory wasteful" approach of generating an extra temporary list and checking its length is actually solidly faster than the simpler, shorter, memory-thrifty one I tend to prefer. Other mixes of list values, Python implementations, availability of memory to "invest" in this speedup, etc, can affect the exact performance, of course.
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. We want to count number of elements in the list that satisfy our given conditions. These conditions can be like, There are different ways to do it. Let’s discuss them one by one, map() function 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.
Advertisements
sum() Function
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,
Output:
Count of odd numbers in a list : 6How 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.
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 : 3Count 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: 9Use 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.
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: 9Count 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 : 1If 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: 9Use 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: 9Use 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: 9reduce() 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,
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