Python | Count the sublists containing the given item in the list

Examples :

  Input:  lst = [1, 3, 5], [1, 3, 5, 7], [1 , 3, 5, 7, 9]] x = 1  Output:  3  Input:  lst = ([`a`], [` a`, `c`, `b`], [` d`]) x = `a`  Output:  2 

Approach # 1: Naive Approach

Count the number of lists containing x . Initialize counter to 0, then run a for loop and check if x exists in each list or not. If so, increase the counter .

# Python3 Counting program
# a list containing a specific element
# in a list of lists

  

def countList (lst, x):

count = 0

for i in range ( len (lst)):

if x in lst [i]:

count + = 1

 

return count

  
Driver code

lst = ( [ `a` ], [ ` a` , `c` , ` b` ], [ `d` ]) 

x = `a`  

print (countList (lst, x))

Exit :

 2 

Approach # 2: Understanding the list (Alternative for the naive)
A simple one-line list comprehension can also help by simply converting the above naive approach to a one-line loop.

# Python3 Program for counting numbers
# a list containing a specific element
# in a list of lists

 

def countList ( lst, x):

 

return sum (x in item for item in lst)

  
Driver code

lst = ([ `a` ], [ `a` , ` c` , `b` ], [ ` d` ]) 

x = `a`

print (countList (lst, x ))

Exit:

 2 

Approach # 3:  Using chain.from_iterable () and Counter

We can use Counter to count the number of "x" lists. Since we don`t want to count "x" more than once for each inner list, we convert each inner list to sets. Then combine these sets of elements into one sequence using chain.from_iterable () .

# Python3 Counting program
# a list containing a specific element
# in a list of lists

from itertools import chain

from collections import Counter

 

def countList (lst, x):

 

return Counter (chain.from_iterable ( set (i) for i in lst)) [x]

 
Driver code

lst = ([ `a` ], [ `a` , ` c` , `b` ], [ `d` ]) 

x = `a`

print (countList (lst, x))

Exit :

 2