Understanding lambda(), map(), and filter() in Python

Python is renowned for its readability, flexibility, and simplicity, making it a favourite among programmers. Among its powerful features are the filter(), map(), and lambda() functions. These tools allow for cleaner, more efficient code by enabling functional programming constructs within Python. In this article, we’ll dive deep into these functions, exploring their syntax, usage, and practical examples.

The Filter Function

The filter() function is used to filter items in an iterable (like lists or tuples) based on a condition or function. It returns only the elements for which the function evaluates to True.

    Syntax:

    filter(function, iterable)
    • function: A function that returns a boolean (True or False) for each element.
    • iterable: The iterable to be filtered (list, tuple, set, etc.).

    The result is a filter object (an iterator), which you can convert to a list, tuple, or set.

    Example 1

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    # Filter out even numbers
    even_numbers = filter(lambda x: x % 2 == 0, numbers)
    print(list(even_numbers))  
    
    # Output: 
    [2, 4, 6, 8, 10]

    In this example, the lambda function (lambda x: x % 2 == 0) is applied to each element of the list, and only those that are divisible by 2 (even numbers) are returned.

    Example 2

    ages = [5, 12, 17, 18, 24, 32]
    
    def myFunc(x):
      if x < 18:
        return False
      else:
        return True
    
    adults = filter(myFunc, ages)
    
    for x in adults:
      print(x)
    
    
    #output
    18
    24
    32

    Example 3

    # Define a function to check if a string has more than 5 characters
    def longer_than_five(s):
        return len(s) > 5
    
    words = ["apple", "banana", "pear", "watermelon", "grape"]
    # Use filter with the longer_than_five function
    long_words = filter(longer_than_five, words)
    
    print(list(long_words))  # Output: ['banana', 'watermelon']

    Example 4

    # Define a function to check if a number is even
    def is_even(num):
        return num % 2 == 0
    
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    # Use filter with the is_even function
    even_numbers = filter(is_even, numbers)
    
    print(list(even_numbers))  # Output: [2, 4, 6, 8, 10]

    Example 5

    # Define a function to check if a number is positive
    def is_positive(n):
        return n > 0
    
    numbers = [-10, -5, 0, 5, 10, 15]
    # Use filter with the is_positive function
    positive_numbers = filter(is_positive, numbers)
    
    print(list(positive_numbers))  # Output: [5, 10, 15]

    Example 5

    # Define a function to check if a person is an adult
    def is_adult(person):
        return person['age'] >= 18
    
    people = [
        {'name': 'John', 'age': 17},
        {'name': 'Jane', 'age': 22},
        {'name': 'Tom', 'age': 16},
        {'name': 'Lucy', 'age': 19}
    ]
    
    # Use filter with the is_adult function
    adults = filter(is_adult, people)
    print(list(adults))  
    
    # Output: [{'name': 'Jane', 'age': 22}, {'name': 'Lucy', 'age': 19}]
    

    The Map Function

    The map() function applies a given function to all the items in an iterable and returns a new iterable (a map object) with the results.

    Syntax

    map(function, iterable)
    • function: A function to apply to each element.
    • iterable: The iterable (like a list, tuple, etc.).

    Just like filter(), the result is a map object, which can be converted into a list, tuple, or set.

    Example 1

    numbers = [1, 2, 3, 4, 5]
    
    # Square each number
    squared_numbers = map(lambda x: x ** 2, numbers)
    print(list(squared_numbers))  
    
    # Output: 
    [1, 4, 9, 16, 25]

    Here, the lambda function squares each element in the numbers list, producing a new list of squared values.

    Example 2

    def myfunc(a):
      return len(a)
    
    x = map(myfunc, ('apple', 'banana', 'cherry'))
    
    
    #convert the map into a list, for readability:
    print(list(x))
    
    #output
    [5, 6, 6]

    The Lambda Function

    lambda functions are anonymous, one-liner functions defined using the lambda keyword. They are used primarily for short, throwaway functions or as arguments in higher-order functions like filter() and map().

    Syntax

    lambda arguments: expression
    • arguments: Comma-separated parameters.
    • expression: The single expression to be evaluated and returned.

    lambda functions are commonly used with filter() and map() but can also be assigned to variables.

    Use lambda functions when an anonymous function is required for a short period of time.

    Example 1

    # A lambda function that adds two numbers
    add = lambda x, y: x + y
    print(add(3, 5))  
    
    # Output: 8

    This example shows a simple lambda function that takes two arguments and returns their sum.

    Example 2

    The power of lambda is better shown when you use it as an anonymous function inside another function.

    Say you have a function definition that takes one argument, and that argument will be multiplied by an unknown number:

    def myfunc(n):
      return lambda a : a * n
    
    mydoubler = myfunc(2)
    
    print(mydoubler(11))
    
    #Output 
    2

    Performance Considerations

    While filter(), map(), and lambda() functions offer clean, functional-style solutions, there are performance trade-offs:

    • Readability: Overusing lambda in deeply nested expressions may make the code harder to read. Named functions are often more descriptive.
    • Memory Efficiency: Both filter() and map() return iterators, which are more memory-efficient than lists. However, wrapping these objects in list() or tuple() may negate this benefit.

    Practice

    Example 1

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    # Filter even numbers and square them
    even_squares = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
    
    
    print(list(even_squares))  # Output: [4, 16, 36, 64, 100]

    Example 2

    words = ["apple", "banana", "cherry", "date", "fig", "grape"]
    result = list(map(lambda s: s.upper(), filter(lambda s: 'a' in s, words)))
    
    
    print(result)  # Output: ['APPLE', 'BANANA', 'DATE', 'GRAPE']

    Example 3

    floats = [7.1, 12.6, 3.8, 15.4, 9.7]
    result = list(map(lambda x: round(x), filter(lambda x: x >= 10, floats)))
    
    print(result)  # Output: [13, 15]

    Example 4

    strings = ["cat", "elephant", "dog", "giraffe", "mouse"]
    result = list(map(lambda s: len(s), filter(lambda s: len(s) >= 5, strings)))
    
    print(result)  # Output: [8, 7, 5]

    Example 5

    from datetime import datetime
    date_strings = ["2021-05-15", "2023-08-01", "2024-01-10", "2022-12-31"]
    result = list(map(lambda d: datetime.strptime(d, "%Y-%m-%d"), filter(lambda d: datetime.strptime(d, "%Y-%m-%d").year >= 2023, date_strings)))
    
    print(result)  # Output: [datetime.datetime(2023, 8, 1, 0, 0), datetime.datetime(2024, 1, 10, 0, 0)]

    Conclusion

    The filter(), map(), and lambda() functions are powerful tools in Python’s functional programming arsenal. They allow for concise, readable, and efficient code, especially when dealing with data transformation and filtering tasks. Understanding when and how to use them effectively can significantly improve your coding productivity and the elegance of your solutions.

    Leave a Comment