Member-only story

Why Your Lambda Function Does Not Work

codeforests
5 min readJul 28, 2020

--

<span>Photo by <a href=”https://unsplash.com/@luthermeb?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCop
Photo by Luther Bottrill on Unsplash

Introduction

Lambda function in Python is designed to be a one-liner and throwaway function even without the needs to assign a function name, so it is also known as anonymous function. Comparing to the normal Python functions, you do not need to write the def and return keywords for lambda function, and it can be defined just at the place where you need it, so it makes your code more concise and looks a bit special. In this article, we will be discussing some unexpected results you may have encountered when you are using lambda function.

Basis usage of lambda

Let’s cover some basis of lambda function before we dive into the problems we are going solve in this article.

Below is the syntax to define lambda function:

As you can see lambda function can be defined with or without arguments, and take note that it only accepts one line of expression, not any of the Python statements. Expressions can be also statements, the difference is that you are able to evaluate a expression into values (or objects), e.g.: 2**2, but you may not be able to evaluate a statement like while(True): into a value. You can think there is an implicit “return” keyword before the expression, so your expression must be eventually computed into a value.

--

--

codeforests
codeforests

Written by codeforests

Resources and tutorials for python, data science and automation solutions

No responses yet