Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Member-only story

What is the lambda function in Python?

--

Hi, in this story I try to explain what is the lambda function(s) and how to use it.

The lambda keyword is used to create small, simple functions without giving them a name. These are called "lambda functions" or "anonymous functions."

Specifications

  1. Anonymous: Lambda functions don’t have a name.
  2. Single Expression: They can only contain one expression, not multiple statements.
  3. Inline: They are often used in places where you need a small function for a short period of time.
lambda arguments: expression

Imagine you want a function that adds 10 to a number. Normally, you would write:

def square(x):
return x**2

With a lambda function, you can write the same thing in one line:

square= lambda x: x**2

Lambda functions are often used when you need a small function for a short period, like in sorting or filtering lists.

numbers = [1, 2, 3, 4]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4]

--

--