Python | Count the sublists containing given element in a list

Given a list of lists, write a Python program to count the number of sublists containing the given element x.

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 count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to count number of
# list containing a certain 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))

chevron_right


Output:

2

 
Approach #2 : List comprehension (Alternative for naive)
A simple one-liner list comprehension can also do the job by simply converting the above mentioned Naive approach into one-liner for loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to count number of
# list containing a certain 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))

chevron_right


Output:

2

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

We can use Counter to count how many lists ‘x’ occurs in. Since we don’t want to count ‘x’ for more than once for each inner list, we’ll convert each inner list to sets. After this, join those sets of elements into one sequence using chain.from_iterable().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to count number of
# list containing a certain 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))

chevron_right


Output:

2


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.