Count the sublists containing given element in a list in Python

PythonServer Side ProgrammingProgramming

The elements in a given list can also be present as another string in another variable. In this article we'll see how many times a given stream is present in a given list.

With range and len

We use the range and len function to keep track of the length of the list. Then use the in condition to find the number of times the string is present as an element in a list. A count variable initialized to zero keeps incrementing whenever the condition is met.

Example

 Live Demo

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'

# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = 0
for i in range(len(Alist)):
   if Bstring in Alist[i]:
      count += 1
print("Number of times the string is present in the list:\n",count)

Output

Running the above code gives us the following result −

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

With sum

We use to in conditions to match the string as an element in the given list. And finally apply the sum function to get the count whenever the match condition is positive.

Example

 Live Demo

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = sum(Bstring in item for item in Alist)
print("Number of times the string is present in the list:\n",count)

Output

Running the above code gives us the following result −

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

With Counter and chain

The itertools and collecitons modules give service the chain and counter functions which can be used to get the count of all the elements of the list which match with the string.

Example

 Live Demo

from itertools import chain
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'M'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
cnt = Counter(chain.from_iterable(set(i) for i in Alist))['M']
print("Number of times the string is present in the list:\n",cnt)

Output

Running the above code gives us the following result −

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
M
Number of times the string is present in the list:
2
raja
Published on 04-Jun-2020 11:35:37
Advertisements