This is exactly the type of situation the filter
function is intended for:
>>> mylist = ['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc', 'aaaa', 'bbbb', 'cccc']
>>> minlist = list(filter(lambda i: len(i) == 4, mylist))
>>> minlist
['aaaa', 'bbbb', 'cccc']
filter
takes two arguments: the first is a function, and the second is an iterable. The function will be applied to each element of the iterable, and if the function returns True
, the element will be kept, and if the function returns False
, the element will be excluded. filter
returns the result of filtering these elements according to the passed in function
As a sidenote, the filter
function returns a filter
object, which is an iterator, rather than a list
(which is why the explicit list
call is included). So, if you're simply iterating over the values, you don't need to convert it to a list
as it will be more efficient