All categories
    PythonAdvanced

    Lambda & Functional

    Functional programming in Python: lambda functions, map, filter, reduce, and sorted with custom keys for clean data processing.

    01Map with lambda

    main.py
    nums = [1, 2, 3, 4]
    doubled = list(map(lambda x: x * 2, nums))
    print(doubled)
    Output
    [2, 4, 6, 8]

    02Filter with lambda

    main.py
    nums = [1, 2, 3, 4, 5, 6]
    evens = list(filter(lambda x: x % 2 == 0, nums))
    print(evens)
    Output
    [2, 4, 6]

    03Reduce to a single value

    main.py
    from functools import reduce
    nums = [1, 2, 3, 4]
    product = reduce(lambda a, b: a * b, nums)
    print(product)
    Output
    24

    04Sort with a key

    main.py
    words = ["banana", "apple", "cherry"]
    by_length = sorted(words, key=lambda w: len(w))
    print(by_length)
    Output
    ['apple', 'banana', 'cherry']