How to remove a string from a list of strings if its length is lower than the length of the string with max length in Python 2.7?
list, python, string-length
Solution
Use a list comprehension and `max`:
>>> test = ['cat', 'dog', 'house', 'a', 'range', 'abc']
>>> max_ = max(len(x) for x in test) #Find the length of longest string.
>>> [x for x in test if len(x) == max_] #Filter out all strings that are not equal to max_
['house', 'range']
Problem
How to remove a string from a list of strings if its length is lower than the length of the string with max length in Python 2.7? Basically, if I have a list such as: ``` test = ['cat', 'dog', 'house', 'a', 'range', 'abc'] max_only(test) ``` The output should be: ``` ['house', 'range'] ``` 'cat''s length is 3, 'dog' is 3, 'house' is 5, 'a' is 1, 'range' is 5, 'abc' is 3. The string with the highest length are 'house' and 'range', so they're returned. I tried with something like this but, of course, it doesn't work :) ``` def max_only(lst): ans_lst = [] for i in lst: ans_lst.append(len(i)) for k in range(len(lst)): if len(i) < max(ans_lst): lst.remove(lst[ans_lst.index(max(ans_lst))]) return lst ``` Could you help me? Thank you. EDIT: What about the same thing for the min length element?