filter
can be used to extract elements from a list that meet a certain condition. It's probably the closest equivalent to Perl's grep function. lambda
expression to filter the numbers whose length is less or equal to four characters: #!/usr/bin/python nums = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] # # Use a lambda function to filter the numbers whose length # is less or equal to four characters: # nums_ = filter(lambda L: len(L) <= 4, nums) for num in nums_: print(num)
filter(…)
is different from list comprehension in that filter(…)
returns an iterator (a filter object) while the list comprehension returns a list.