lambda function in python

lambda function is defined using lambda keyword. It’s an¬†anonymous function without name.

Syntax:

lambda arguments: expression

Add two numbers using lambda function

# Add two numbers
add = lambda x, y: x + y

result = add(10, 20)
print(result)

Output: 30

 

Square a number

# Square a number
sqr = lambda x: x**2

result = sqr(10)
print(result)

Output: 100

 

Increment a number

# Increment of a number
def do_increment(num):
    """
    Increase a number
    :param num: int
    :return: int
    """

    return lambda x: x + num

increase = do_increment(5)
result = increase(10)
print(result)

Output: 15

 

Use lambda with map function

# Use with map
nums = range(1, 10)
new_mapped_nums = map(lambda x: x + 1, nums)

print(list(new_mapped_nums))

Output: [2, 3, 4, 5, 6, 7, 8, 9, 10]

 

Use lambda with filter

# Use with filter
nums = range(1, 15)
new_filtered_nums = filter(lambda x: x % 2 == 0, nums)

print(list(new_filtered_nums))

Output: [2, 4, 6, 8, 10, 12, 14]

 

Use lambda with reduce

# Use with reduce
nums = range(1, 10)
new_reduced_nums = reduce(lambda x, y: x + y, nums)

print(new_reduced_nums)

Output: 45

 

Find length of each words in a string using lambda and list comprehension

st = 'My name is Bhawani Shanker'
words_length = [(lambda x: len(x))(x) for x in st.split()]

print(list(words_length))

Output: [2, 4, 2, 7, 7]

 

Find length of each words in a string using lambda and map

st = 'World is so beautiful'
wl = map(lambda x: len(x), st.split())

print(list(wl))

Output: [5, 2, 2, 9]

Source code

1 thought on “lambda function in python”

Leave a Reply

Your email address will not be published. Required fields are marked *