Given a list of lists, write a Python program to count the number of sublists containing the given element x.
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.
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.
Approach #3 : Using
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
- Python | Count unique sublists within list
- Python | Print all sublists of a list
- Python - Group Sublists by another List
- Python | Split a list into sublists of given lengths
- Python | Sort all sublists in given list of strings
- Python | Remove repeated sublists from given list
- Python | Sort list of lists by the size of sublists
- Python | Split list of strings into sublists based on length
- Python | Count occurrences of an element in a list
- Python | List Element Count with Order
- Python | Count the elements in a list until an element is a Tuple
- Python | Adding value to sublists
- Python | Merge elements of sublists
- Python | Remove all sublists outside the given range
- Python | Add the occurrence of each number as sublists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.