Search notes:

Python: filter

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.

Filter in combination with a lambda function

The following snippet uses a 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)
Github repository about-Python, path: /builtin-functions/filter/lambda.py

See also

filter(…) is different from list comprehension in that filter(…) returns an iterator (a filter object) while the list comprehension returns a list.
Python: Built in functions

Index