I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can’t implement the search for the a char:
def find_max_list(list):
list_len = [len(i) for i in list]
print(max(list_len))
find_max_list(your_list)
>Solution :
Try this:
def find_max_list(lst):
lst_len = max(('a' in x, len(x)) for x in lst)
print(lst_len)
This piece of code creates a list of tuples where the first element is True or False (depending on ‘a’ being present or not in the list) and the second element is just the length of a list. Then you calculate the max, keeping in mind that False < True, and that first elements are evaluated first.
An alternative approach is to filter out those lists not containing ‘a’:
def find_max_list(lst):
lst_len = max(len(x) for x in lst if 'a' in x)
print(lst_len)