Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Lambda Functions in Python | Functions in Python
Introduction to Python (dev copy)

bookLambda Functions in Python

All the functions we've created up until now are stored in memory after the code runs for the first time. However, there are times when you might not want to create a standalone function, especially for straightforward tasks. In these situations, you can use Python's lambda function, which is essentially an anonymous function. Here's the syntax:

lambda var1, var2, ... : expression

As an illustration, let's revisit our initial function. We can refactor it using a lambda function to return the squared sum of two numbers:

1234
# Define lambda function sq = lambda x, y: (x + y)**2 # Test it print('Sum of 2 and 3 squared is', sq(2, 3))
copy

Note

As you might infer, not all functions we've discussed can be converted into lambda functions. Typically, lambda functions are best suited for concise operations that fit within a single line.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 6. Kapitel 11

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

Ställ mig frågor om detta ämne

Sammanfatta detta kapitel

Visa verkliga exempel

Awesome!

Completion rate improved to 1.64

bookLambda Functions in Python

Svep för att visa menyn

All the functions we've created up until now are stored in memory after the code runs for the first time. However, there are times when you might not want to create a standalone function, especially for straightforward tasks. In these situations, you can use Python's lambda function, which is essentially an anonymous function. Here's the syntax:

lambda var1, var2, ... : expression

As an illustration, let's revisit our initial function. We can refactor it using a lambda function to return the squared sum of two numbers:

1234
# Define lambda function sq = lambda x, y: (x + y)**2 # Test it print('Sum of 2 and 3 squared is', sq(2, 3))
copy

Note

As you might infer, not all functions we've discussed can be converted into lambda functions. Typically, lambda functions are best suited for concise operations that fit within a single line.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 6. Kapitel 11
some-alt