0 out of 464 challenges solved
Write a Python function `count_element_in_list` that takes two arguments: 1. A list of sublists (`list1`). 2. An element (`x`). The function should return the number of sublists in `list1` that contain the element `x`. #### Example Usage ```python [main.nopy] print(count_element_in_list([[1, 3], [5, 7], [1, 11], [1, 15, 7]], 1)) # Output: 3 print(count_element_in_list([['A', 'B'], ['A', 'C'], ['A', 'D', 'E'], ['B', 'C', 'D']], 'A')) # Output: 3 print(count_element_in_list([['A', 'B'], ['A', 'C'], ['A', 'D', 'E'], ['B', 'C', 'D']], 'E')) # Output: 1 ``` #### Constraints - The input list will only contain sublists. - The sublists can contain any hashable elements. - The function should handle empty sublists and an empty input list gracefully.
def count_element_in_list(list1, x): """ Count the number of sublists in list1 that contain the element x. Args: list1 (list of list): A list containing sublists. x (any): The element to search for in the sublists. Returns: int: The count of sublists containing the element x. """ # Initialize a counter to zero count = 0 # Iterate through each sublist in the list for sublist in list1: # Check if the element x is in the current sublist if x in sublist: # Increment the counter count += 1 # Return the final count return count