Python Лямбда-функції з ПРИКЛАДАМИ

⚡ Розумний підсумок

Lambda functions in Python are small anonymous functions defined with the lambda keyword instead of def. They hold a single expression, take any number of arguments, and are often passed directly to built-ins such as map(), filter(), and sorted().

  • 🔑 Lambda keyword: A lambda is written as lambda arguments: expression, with no def, no name, and no explicit return statement.
  • 🧮 Single expression: The body holds exactly one expression whose value is returned automatically, so statements and multiple lines are not allowed.
  • 🔗 Built-in pairing: Lambdas are commonly passed to map(), filter(), reduce(), and sorted() to transform or select items in a sequence.
  • IIFE: A lambda can be defined and called immediately using the pattern (lambda x: x + x)(2), returning a result at once.
  • 🇧🇷 Versus def: Regular functions need a name and can hold many statements, while lambdas trade that power for compact, one-line syntax.
  • 🤖 Допомога AI: AI assistants such as GitHub Copilot generate lambda expressions for map, filter, and sort keys from a short prompt.

Python Лямбда-функції

Що таке лямбда-функція Python?

A Лямбда-функція в Python програмування є анонімною функцією або функцією без імені. Це невелика та обмежена функція, що містить не більше одного рядка. Як і звичайна функція, лямбда-функція може мати кілька аргументів з одним виразом.

In Python, лямбда-вирази (або лямбда-форми) використовуються для створення анонімних функцій. Для цього ви скористаєтеся лямбда ключове слово (так само, як ви використовуєте захист для визначення нормальних функцій). Кожна анонімна функція, яку ви визначаєте в Python матиме 3 основні частини:

  • Ключове слово лямбда.
  • Параметри (або зв'язані змінні) і
  • Тіло функції.

Лямбда-функція може мати будь-яку кількість параметрів, але тіло функції може містити лише один вираз. Крім того, лямбда записується в одному рядку коду і може бути викликана негайно. Ви побачите все це в дії в наступних прикладах.

Синтаксис і приклади

Формальний синтаксис для написання лямбда-функції наведено нижче:

lambda p1, p2: expression

Тут p1 і p2 — параметри, які передаються лямбда-функції. Ви можете додати скільки завгодно параметрів або кілька.

However, notice that we do not use brackets around the parameters as we do with regular functions. The last part (expression) is any valid Python expression that operates on the parameters you provide to the function.

Приклад 1

Тепер, коли ви знаєте про лямбда-вирази, давайте спробуємо це на прикладі. Отже, відкрийте свій IDLE і введіть наступне:

adder = lambda x, y: x + y
print (adder (1, 2))

Code Пояснення

Тут ми визначаємо змінну, яка буде зберігати результат, повернутий лямбда-функцією.

1. Ключове слово лямбда, яке використовується для визначення анонімної функції.

2. x і y – це параметри, які ми передаємо лямбда-функції.

3. Це тіло функції, яка додає 2 параметри, які ми передали. Зверніть увагу, що це один вираз. Ви не можете написати кілька операторів у тілі лямбда-функції.

4. Ми викликаємо функцію та друкуємо повернуте значення.

Приклад 2

That was a basic example to understand the fundamentals and syntax of lambda. Let us now try to print out a lambda and see the result. Again, open your IDLE і введіть наступне:

#What a lambda returns
string='some kind of a useless lambda'
print(lambda string : print(string))

Тепер збережіть файл і натисніть F5, щоб запустити програму. Це результат, який ви повинні отримати.

вихід:

<function <lambda> at 0x00000185C3BF81E0>

What is happening here? Let us look at the code to understand further.

Code Пояснення:

1. Here, we define a рядок that you will pass as a parameter to the lambda.

2. We declare a lambda that calls a print statement and prints the result.

But why does the program not print the string we pass? This is because the lambda itself returns a function object. In this example, the lambda is not being званий by the print function but is simply повернення the function object and the memory location where it is stored. That is what gets printed at the console.

Приклад 3

Однак, якщо ви напишете таку програму:

#What a lambda returns #2
x="some kind of a useless lambda"
(lambda x : print(x))(x)

And run it by hitting F5, you will see an output like this.

вихід:

some kind of a useless lambda

Now, the lambda is being called, and the string we pass gets printed at the console. But what is that weird syntax, and why is the lambda definition covered in brackets? Let us understand that now.

Code Пояснення:

1. Here is the same string we defined in the previous example.

2. In this part, we are defining a lambda and calling it immediately by passing the string as an argument. This is something called an IIFE, and you will learn more about it in the upcoming sections of this tutorial.

Приклад 4

Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE і в новому файлі введіть наступне:

#A REGULAR FUNCTION
def guru( funct, *args ):
funct( *args )
def printer_one( arg ):
return print (arg)
def printer_two( arg ):
print(arg)
#CALL A REGULAR FUNCTION 
guru( printer_one, 'printer 1 REGULAR CALL' )
guru( printer_two, 'printer 2 REGULAR CALL \n' )
#CALL A REGULAR FUNCTION THRU A LAMBDA
guru(lambda: printer_one('printer 1 LAMBDA CALL'))
guru(lambda: printer_two('printer 2 LAMBDA CALL'))

Now, save the file and hit F5 to run the program. If you did not make any mistakes, the output should be something like this.

вихід:

printer 1 REGULAR CALL

printer 2 REGULAR CALL

printer 1 LAMBDA CALL

printer 2 LAMBDA CALL

Code Пояснення:

1. A function called guru that takes another function as the first parameter and any other arguments following it.

2. printer_one is a simple function which prints the parameter passed to it and returns it.

3. printer_two is similar to printer_one but without the return statement.

4. In this part, we are calling the guru function and passing the printer functions and a string as parameters.

5. This is the syntax to achieve the fourth step (i.e., calling the guru function) but using lambdas.

У наступному розділі ви дізнаєтеся, як використовувати лямбда-функції з карта (), зменшити () та filter () in Python.

Використання лямбда з Python вбудовані

Лямбда-функції забезпечують елегантний і потужний спосіб виконання операцій за допомогою вбудованих методів Python. Це можливо, оскільки лямбда-вирази можна негайно викликати та передати як аргумент до цих функцій.

ІІФЕ в Python Лямбда

IIFE стенди для негайно викликав виконання функції. It means that a lambda function is callable as soon as it is defined. Let us understand this with an example; fire up your IDLE і введіть наступне:

 (lambda x: x + x)(2)

Ось результат і пояснення коду:

Ця можливість негайного виклику лямбда-виразів дозволяє використовувати їх у таких функціях, як map() і reduce(). Це корисно, оскільки ви можете не захотіти використовувати ці функції знову.

лямбда у filter()

Функція фільтра використовується для вибору окремих елементів із послідовності елементів. Послідовність може бути будь-яким ітератором, таким як списки, набори, кортежі тощо.

The elements which will be selected are based on some pre-defined constraint. It takes 2 parameters:

  • Функція, яка визначає обмеження фільтрації
  • Послідовність (будь-який ітератор, наприклад списки, кортежі тощо)

Наприклад,

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = filter (lambda x: x > 4, sequences) 
print(list(filtered_result))

Ось висновок:

[10, 8, 7, 5, 11]

Code Пояснення:

1. У першому операторі ми визначаємо список, який називається послідовностями, який містить деякі числа.

2. Тут ми оголошуємо змінну під назвою filtered_result, яка зберігатиме відфільтровані значення, які повертає функція filter().

3. Лямбда-функція, яка виконується з кожним елементом списку та повертає значення true, якщо воно більше 4.

4. Надрукувати результат, повернутий функцією фільтра.

лямбда-вирази в map()

The map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters:

  1. A function that defines the operation to perform on the elements
  2. Одна або кілька послідовностей

Наприклад, ось програма, яка друкує квадрати чисел у заданому списку:

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences) 
print(list(filtered_result))

вихід:

 [100, 4, 64, 49, 25, 16, 9, 121, 0, 1]

Code Пояснення:

1. Here, we define a list called sequences which contains some numbers.

2. We declare a variable called filtered_result which will store the mapped values.

3. A lambda function which runs on each element of the list and returns the square of that number.

4. Print the result returned by the map function.

лямбда в зменшити()

Функція зменшення, як map(), використовується для застосування операції до кожного елемента в послідовності. Однак вона відрізняється від карти своєю роботою. Це кроки, за якими слідує функція reduce() для обчислення результату:

Крок 1) Виконайте визначену операцію над першими 2 елементами послідовності.

Крок 2) Save this result.

Крок 3) Виконайте операцію зі збереженим результатом і наступним елементом послідовності.

Крок 4) Повторюйте, доки не залишиться елементів.

Він також приймає два параметри:

  1. Функція, яка визначає операцію, яку потрібно виконати
  2. Послідовність (будь-який ітератор, наприклад списки, кортежі тощо)

Наприклад, ось програма, яка повертає добуток усіх елементів у списку:

from functools import reduce
sequences = [1,2,3,4,5]
product = reduce (lambda x, y: x*y, sequences)
print(product)

Ось висновок:

120

Code Пояснення:

1. Import reduce from the functools module.

2. Here, we define a list called sequences which contains some numbers.

3. We declare a variable called product which will store the reduced value.

4. A lambda function that runs on each element of the list. It will return the product of that number as per the previous result.

5. Print the result returned by the reduce function.

Навіщо (і чому ні) використовувати лямбда-функції?

Як ви побачите в наступному розділі, лямбда обробляються так само, як і звичайні функції на рівні інтерпретатора. У певному сенсі можна сказати, що лямбда-вирази забезпечують компактний синтаксис для написання функцій, які повертають один вираз.

However, you should know when it is a good idea to use lambdas and when to avoid them. In this section, you will learn some of the design principles used by Python developers when writing lambdas.

One of the most common use cases for lambdas is in functional programming, as Python підтримує парадигму (або стиль) програмування, відому як функціональне програмування.

It allows you to provide a function as a parameter to another function (for example, in map, filter, etc.). In such cases, using lambdas offers an elegant way to create a one-time function and pass it as the parameter.

Коли не слід використовувати Lambda?

Ви ніколи не повинні писати складні лямбда-функції у робочому середовищі. Кодерам, які обслуговують ваш код, буде дуже важко його розшифрувати. Якщо ви створюєте складні однорядкові вирази, було б набагато краще визначити правильну функцію. Рекомендуємо пам’ятати, що простий код завжди кращий за складний.

Лямбда проти звичайних функцій

As previously stated, lambdas are just functions which do not have an identifier bound to them. In simpler words, they are functions with no names (hence, anonymous). Here is a table to illustrate the difference between lambdas and regular functions in Python.

Лямбди Регулярні функції
Синтаксис:

lambda x : x + x
Синтаксис:

def (x) :
return x + x 
Лямбда-функції можуть мати лише одне вираження у своєму тілі. Звичайні функції можуть мати кілька виразів і операторів у своєму тілі.
Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. Звичайні функції повинні мати назву та підпис.
Лямбда-вирази не містять оператора return, оскільки тіло повертається автоматично. Functions which need to return a value should include a return statement.

Explanation of the differences

Основна відмінність між лямбда-функцією та звичайною функцією полягає в тому, що лямбда-функція обчислює лише один вираз і дає об’єкт функції. Отже, ми можемо назвати результат лямбда-функції та використовувати його в нашій програмі, як ми робили в попередньому прикладі.

Звичайна функція для наведеного вище прикладу виглядатиме так:

def adder (x, y):
return x + y 
print (adder (1, 2))

Тут ми повинні визначити a ім'я для функції, яка Умови повернення результат, коли ми call it. A lambda function does not contain a return statement because it will have only a single expression which is always returned by default. You do not even have to assign a lambda either, as it can be immediately invoked (see the previous section). As you will see, lambdas become particularly powerful when we use them with Pythonвбудовані функції.

Однак ви можете все ще дивуватися, чим лямбда-вирази відрізняються від функції, яка повертає один вираз (як наведений вище). На рівні перекладача особливої ​​різниці немає. Це може здатися дивним, але будь-яка лямбда-функція, яку ви визначаєте в Python розглядається інтерпретатором як звичайна функція.

At the bytecode level, the two definitions are handled in the same way by the Python interpreter. Now, you cannot name a function лямбда оскільки він зарезервований Python, but any other function name will yield the same bytecode.

Поширені запитання

Yes. A lambda can use a conditional expression such as lambda x: ‘even’ if x % 2 == 0 else ‘odd’. It cannot hold a full if statement, because the body of a lambda must be a single expression rather than a block of statements.

Generally no. PEP 8 recommends using def when a function needs a name, because binding a lambda to a variable gives it a name yet loses the clearer traceback that def provides. Lambdas are best passed directly to functions such as sorted(), map(), or filter().

No. At the bytecode level Python treats a lambda and an equivalent def the same way, so there is no speed advantage. A lambda only saves a line of code; it does not execute faster than a named function doing identical work.

Yes. A lambda can read variables from the enclosing scope, forming a closure. Inside a loop, be careful: the lambda captures the variable itself, not its current value, so use a default argument like lambda x, n=n: x + n to freeze it.

Pass a lambda as the key argument to sorted() or list.sort(). For example, sorted(users, key=lambda u: u[‘age’]) orders items by age. The lambda tells Python which value to compare for each element, giving concise custom sorting without a separate named function.

Not directly, because an anonymous lambda has no name to reference. You can work around this by assigning the lambda to a variable and calling that name, but a normal def function is the clearer and recommended choice for recursion.

Lambdas power quick, inline transformations in AI and machine learning code. Data scientists pass them to pandas .apply(), map(), and filter() to clean or reshape data, and as key functions for sorting features, keeping preprocessing compact inside larger training pipelines.

GitHub Copilot suggests complete lambda expressions from a short comment or the surrounding code, including the correct parameters and expression for map(), filter(), or sorted() calls. It can also propose converting a verbose lambda into a clearer named function when readability matters.

Підсумуйте цей пост за допомогою: