Python count elements in list with condition

Count of elements matching particular condition in Python

In this article we will see how to get some selected elements out of a Python list. So we need to design some condition and only the elements satisfying that condition should be picked and their count to be printed.

Wit in and sum

In this approach we use in condition to pick the elements and use some to get their count. 1 is used if the element is present else 0 is used for the result of in condition.

Example

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt = sum(1 for i in Alist if i in('Mon','Wed')) print("Number of times the condition is satisfied in the list:\n",cnt)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3

With map and lambda

Here also used in condition but also use lambda and map functions. Final we apply the sum function to get the count.

Читайте также:  Php copy with replace

Example

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt=sum(map(lambda i: i in('Mon','Wed'), Alist)) print("Number of times the condition is satisfied in the list:\n",cnt)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3

With reduce

The reduce function applies a particular function to all the elements in a list supplied to it as an argument. We use it along with a in condition finally producing the count of the elements matching the condition.

Example

from functools import reduce Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt = reduce(lambda count, i: count + (i in('Mon','Wed')), Alist, 0) print("Number of times the condition is satisfied in the list:\n",cnt)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3

Источник

Python : Count elements in a list that satisfy certain conditions

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,

Frequently Asked:

Use map() & sum() to count elements in a list that satisfy certain conditions

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.

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

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)
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.

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))
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)
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)
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)
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)
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)
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)
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)
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()
**** 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

Источник

Оцените статью