Count of elements matching particular condition in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

Example

 Live Demo

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

 Live Demo

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
raja
Published on 04-Jun-2020 11:31:05
Advertisements