Lambda Functions in Python

Python Shorts — Part 1

Oliver S
Level Up Coding

--

In this series of posts we will cover neat Python features every developer should know about. In Part 1, we take a look at lambda functions.

Photo by Chris Ried on Unsplash

Lambda functions in Python are small, anonymous functions, mainly used for brevity and convenience.

Their syntax is as follows:

lambda arguments: expression

They can take an arbitrary number of arguments, and will execute expression and return its value.

As mentioned above, this is often used for convenience and to shorten code, e.g. in iterators or generator function.

As afirst example, consider defining a lambda to square a number:

square = lambda x: x**2
print(square(5))

Here, we make use of the fact that functions are first class objects in Python, assign our lambda function to the variable square, and later call it and print the result.

Let us now put this into a somewhat more realistic setting using Python’s map function: this takes a function f and a list, and returns a new list, in which f was applied to all values in it:

standard_list = [0, 1, 2, 3, 4, 5]
squared_list = list(map(lambda x: x**2, standard_list))
print(squared_list)

That’s it for Part 1, thanks for tuning in — and feel free to come back for more:

--

--