Python function anonymous function

Python Anonymous Function [In-Depth Tutorial]

In Python, anonymous functions are also called lambda functions. An anonymous function is a function that does not have a name and is defined on a single line using the lambda keyword. These functions are commonly used for simple operations that do not require a full function definition, such as filtering or mapping data.

Lambda functions are useful in Python because they offer a more concise way to define functions that only need to be used once or a few times. Instead of defining a named function with a full function definition, you can define a lambda function on a single line and pass it as an argument to another function or use it in a list comprehension.

Lambda functions are often used with functions like filter() , map() , and reduce() to perform operations on lists or other iterable objects. They are also useful for defining small callback functions that can be passed to other functions as arguments.

For example, if you have a list of numbers and you want to filter out all the even numbers, you could use a lambda function with the filter() function:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] filtered_numbers = list(filter(lambda x: x % 2 != 0, numbers)) print(filtered_numbers)

As you can see, the lambda function is defined inline with the filter() function and filters out all the even numbers from the original list. This is a more concise and efficient way of achieving the same result as using a full named function definition.

Syntax and structure

Lambda functions in Python have a simple syntax and structure. They start with the lambda keyword, followed by the function’s input parameters (if any), separated by commas, and then a colon. After the colon, you specify the function’s logic or expression, which is evaluated and returned when the lambda function is called.

Here is an example of a lambda function that takes two parameters and returns their sum:

Arguments and parameters

Lambda functions can take any number of input parameters, separated by commas, just like regular functions. These parameters can be either positional or keyword arguments.

Here is an example of a lambda function that takes a single positional argument:

And here is an example of a lambda function that takes a single keyword argument:

You can also use default parameter values in lambda functions, just like in regular functions:

Return values

Like regular functions, lambda functions can return values. The value that a lambda function returns is the result of the expression that follows the colon in the lambda function’s definition.

Here is an example of a lambda function that returns the square of its input parameter:

Читайте также:  Http get java header

Differences between lambda and regular functions

There are several key differences between lambda functions and regular functions in Python. One of the most significant differences is that lambda functions are anonymous and have no name. They are defined inline and only used where they are defined, while regular functions have names and can be defined in one place and used in many places.

Another difference is that lambda functions can only contain a single expression or statement, whereas regular functions can contain multiple statements and a return statement.

Finally, lambda functions are typically used for simple operations that do not require a full function definition, while regular functions are used for more complex operations or operations that need to be reused multiple times in a program.

Common use cases to use Anonymous function

1. Sorting

Lambda functions can be used to define the key function used by Python’s built-in sort() and sorted() functions. The key function takes a single argument and returns a value that is used to determine the order of the items being sorted.

For example, if you have a list of dictionaries that you want to sort by a particular key, you can use a lambda function to define the key function:

students = [ , , , ] students_sorted_by_grade = sorted(students, key=lambda student: student['grade'], reverse=True)

In this example, the lambda function takes a single argument ( student ) and returns the value of the ‘grade’ key in the dictionary. This lambda function is used as the key argument to the sorted() function, which sorts the list of dictionaries in descending order based on the ‘grade’ key.

2. Filtering

Lambda functions can be used to define the filtering logic used by Python’s built-in filter() function. The filter() function takes a function and an iterable as input, and returns a new iterable containing only the elements of the original iterable for which the function returns True .

For example, if you have a list of numbers and you want to filter out all the even numbers, you can use a lambda function to define the filtering logic:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] filtered_numbers = list(filter(lambda x: x % 2 != 0, numbers))

In this example, the lambda function takes a single argument ( x ) and returns True if x is not divisible by 2 (i.e., if x is odd). This lambda function is used as the function argument to the filter() function, which returns a new list containing only the odd numbers from the original list.

3. Mapping

Lambda functions can be used to define the mapping logic used by Python’s built-in map() function. The map() function takes a function and one or more iterables as input, and returns a new iterable containing the results of applying the function to the corresponding elements of the input iterables.

For example, if you have a list of numbers and you want to square each number in the list, you can use a lambda function to define the mapping logic:

numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x ** 2, numbers))

In this example, the lambda function takes a single argument ( x ) and returns the square of x . This lambda function is used as the function argument to the map() function, which returns a new list containing the squares of the numbers in the original list.

Читайте также:  Операции над двумя множествами питон

Some Practical Examples

A lambda function that takes two arguments and returns their sum

A lambda function that takes a single argument and returns its square

A lambda function that takes a list of numbers and returns the sum of the odd numbers

odd_sum = lambda numbers: sum(filter(lambda x: x % 2 != 0, numbers))

In this example, the lambda function takes a single argument ( numbers ) and applies a filter() function to it to return only the odd numbers. The resulting list of odd numbers is then passed to the sum() function to return their sum.

A lambda function that takes a list of strings and returns the length of the longest string

longest_length = lambda strings: max(map(lambda x: len(x), strings))

In this example, the lambda function takes a single argument ( strings ) and applies a map() function to it to return a list of string lengths. The resulting list of lengths is then passed to the max() function to return the length of the longest string.

Summary

In Python, anonymous functions are also known as lambda functions. They are a way to define small, simple functions without having to define them with a full function definition. Anonymous functions are defined using the lambda keyword, followed by the function’s input parameters (if any), separated by commas, and then a colon, followed by the function’s logic or expression. Lambda functions can take any number of input parameters, both positional and keyword, and can return a value based on the expression they contain. Lambda functions are typically used for simple operations that do not require a full function definition, such as filtering, sorting, and mapping data. They are commonly used with built-in Python functions like filter() , map() , and reduce() , and can be defined inline where they are needed. Lambda functions are useful in Python because they offer a more concise and efficient way to define functions that only need to be used once or a few times.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Python Tutorial

  • Python Multiline Comments
  • Python Line Continuation
  • Python Data Types
    • Python Numbers
    • Python List
    • Python Tuple
    • Python Set
    • Python Dictionary
    • Python Nested Dictionary
    • Python List Comprehension
    • Python List vs Set vs Tuple vs Dictionary
    • Python if else
    • Python for loop
    • Python while loop
    • Python try except
    • Python try catch
    • Python switch case
    • Python Ternary Operator
    • Python pass statement
    • Python break statement
    • Python continue statement
    • Python pass Vs break Vs continue statement
    • Python function
    • Python call function
    • Python argparse
    • Python *args and **kwargs
    • Python lambda function
    • Python Anonymous Function
    • Python optional arguments
    • Python return multiple values
    • Python print variable
    • Python global variable
    • Python copy
    • Python counter
    • Python datetime
    • Python logging
    • Python requests
    • Python struct
    • Python subprocess
    • Python pwd
    • Python UUID
    • Python read CSV
    • Python write to file
    • Python delete file
    • Python any() function
    • Python casefold() function
    • Python ceil() function
    • Python enumerate() function
    • Python filter() function
    • Python floor() function
    • Python len() function
    • Python input() function
    • Python map() function
    • Python pop() function
    • Python pow() function
    • Python range() function
    • Python reversed() function
    • Python round() function
    • Python sort() function
    • Python strip() function
    • Python super() function
    • Python zip function
    • Python class method
    • Python os.path.join() method
    • Python set.add() method
    • Python set.intersection() method
    • Python set.difference() method
    • Python string.startswith() method
    • Python static method
    • Python writelines() method
    • Python exit() method
    • Python list.extend() method
    • Python append() vs extend() in list
    • Create your first Python Web App
    • Flask Templates with Jinja2
    • Flask with Gunicorn and Nginx
    • Flask SQLAlchemy

    Источник

    Анонимные функции в Python

    В этой статье вы познакомитесь с анонимными функциями, они же лямбда-функции. Вы узнаете, что это, какой у них синтаксис и как их грамотно использовать.

    Что такое лямбда-функции

    Анонимная функция — функция, которая объявляется без имени.

    Обычно объявление функции сопровождается ключевым словом def . Анонимные же функции объявляются с помощью lambda .

    Именно поэтому анонимные функции еще называют лямбда-функциями.

    Как использовать лямбда-функции

    Ниже показан синтаксис лямбда-функций.

    Синтаксис

    lambda аргументы: выражение

    У лямбда-функций может быть любое число аргументов, но лишь одно выражение. Функция вычисляется и возвращается ее результат. Лямбда-функции используются в ситуациях, когда требуются объекты функций.

    Пример лямбда-функции

    # пример использования лямбда-функции double = lambda x: x * 2 print(double(5))

    В этом примере double = lambda x: x * 2 — лямбда-функция: х — аргумент, x * 2 — выражение, которое выполняет наша функция и результат которого возвращает.

    У лямбда-функции нет имени. Она возвращает функцию, которая присваивается переменной double . Лямбда-функцию можно вызывать как обычную функцию — с помощью круглых скобок. Объявление:

    Почти так же, как и с обычной функцией:

    Как грамотно использовать лямбда-функции

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

    Обычно в Python они используются в качестве аргумента для функций более высокого порядка (функций, принимающих в качестве аргументов другие функции). Часто их используют в комбинации со следующими встроенными функциями: filter() , map() и т. д.

    Функция filter()

    filter() принимает в виде аргументов итерируемый объект и другую функцию.

    Сначала функция проверяет каждый элемент итерируемого объекта. После этого она возвращает новый список, в котором содержатся только те элементы, для которых функция вернула True .

    Пример работы filter()

    # Программа, которая находит четные числа в списке my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list)

    Функция map()

    map() , как и filter(), принимает в качестве аргументов итерируемый объект и другую функцию.

    Функция map() позволяет применить функцию к каждому элементу итерируемого объекта. После этого она возвращает новый список с преобразованными элементами.

    Пример использования map()

    # Программа, которая умножает каждое число в списке на 2 my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list)

    Источник

Оцените статью