Lambda Functions In Python

in #programming7 years ago

Hi there. In this Python programming post, I provide a quick overview of lambda functions. Lambda/anonymous functions are a neat way of defining Python functions with less lines of code.

 


Pixabay Image Source


If I wanted to add ten to a regular number with a regular Python function, I can define a function that takes a numeric input and returns ten plus that input. Then I would need a function call as follows.

 

def add_ten(x):
    return x + 10

test_value = 7

print(add_ten(test_value))

17

 

With a lambda function, I can skip the def part of defining a function and simply do this.

 

add_ten = lambda x: x + 10

print(add_ten(7))

17

 

The numeric value of 7 in the add_ten(7) function call takes on the role of x.

 



Pixabay Image Source


Lambda Functions With Lists

If you have more than one numeric value for the input such as a list of numbers you would use the map() function along with a lambda function. With the map() function, the first argument is the function and the second argument is the list as the input.

 

test_list = [1, 10, -1, 2, 5, 7, 8]

print(list(map(add_ten, test_list)))

[11, 20, 9, 12, 15, 17, 18]

print(list(map(lambda x: x + 10, test_list)))

[11, 20, 9, 12, 15, 17, 18]

 


Pixabay Image Source

 


Thank you for reading.


Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60578.05
ETH 1558.21
USDT 1.00
SBD 0.50