Related Articles

Related Articles

Python | Count the sublists containing given element in a list
  • Last Updated : 16 Mar, 2019

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :