Python lambda functions

| | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

  • Python lambda function or Python anonymous function has no name.
  • We can define an anonymous function using the reserved lambda keyword.
  • The scope of an anonymous function is limited to the current scope in which it is defined.
  • A lambda function can have one or more arguments, but it can only have one expression.
  • The expression is evaluated and the result is returned from the lambda function.
  • Typically used with map (), filter (), and reduce () operations.

Python lambda function syntax

Lambda function syntax:

 lambda arguments: expression 

Anonymous function example

Let’s say we have a function to get the area rectangle.

 def area_of_rectangle (l, w): return l * w print (f’Area of ‚Äã‚ÄãRectangle (4, 5) is {area_of_rectangle (4, 5)} ’) 

Let’s create an anonymous function using the lambda keyword to get the area of ‚Äã‚Äãthe rectangle.



 rectangle_area = lambda x, y: x * y print (f’Area of ‚Äã‚ÄãRectangle (4, 5) is {rectang le_area (4, 5)} ’) 

When to use?

  • For small trivial dach with little complexity.
  • When a function has only one expression.
  • For repetitive tasks that are temporary.
  • If you want the scope of the function to be limited to the current scope only.
  • This is useful when the function argument is another function, such as the map (), filter (), and reduce () functions.

Lambda function with map ()

The map () function takes a function and an iteration as arguments. The function is applied to each element in the iterable, and the updated iterable is returned.

Let’s say we have a list of integers. We have to create a new list by multiplying each element by 10. We can use a lambda function here instead of creating a function for this single use case.

 list_numbers = [1, 2, 3, 4] list_numbers = map (lambda x: x * 10, list_numbers) for num in list_numbers: print (num, end =" ") 

Output:

Lambda- Python Function With Map

With filter ()

The built-in filter () function takes a function and an iteration as an argument. The function is applied to each element of the iteration. If the function returns True, the element is added to the returned iteration.



Let’s say we have a list of integers and we want to remove all odd numbers. The final list should only contain integers.

 list_numbers = [1, 2, 3, 4, 5, 6] list_numbers = filter (lambda x: x% 2 == 0, list_numbers) for num in list_numbers: print (num, end = "") 

 Lambda function with Filter

With reduce ()

The reduce () function is present in the functools module. This function takes a function and a sequence as an argument. The function must take two arguments. The elements from the sequence are passed to the function along with the accumulated value. The end result &one value.

Let’s say we have a list of integers and we want to get the sum of all its elements.

 from functools import reduce list_ints = [1, 2, 3, 4, 5, 6] total = reduce (lambda x, y: x + y, list_ints) print (f’Sum of list_ints elements is {total} ’) 

Reduce example

Python lambda function with no arguments

Yes, we can define a lambda function with no arguments. But it is useless, because there will be nothing to operate on. Let’s see a simple example.

 get_5 = lambda: 5 print (get_5 ()) # 5 

Since the lambda the function always returns the same value, we can simply assign a variable to it. Using without arguments &clear abuse of this feature.



👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Python lambda functions, check other accumulate-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Ken Sikorski

London | 2023-03-25

I was preparing for my coding interview, thanks for clarifying this - Python lambda functions in Python is not the simplest one. I just hope that will not emerge anymore

Marie Ungerschaft

Massachussetts | 2023-03-25

Maybe there are another answers? What Python lambda functions exactly means?. Will use it in my bachelor thesis

Frank Jackson

Shanghai | 2023-03-25

I was preparing for my coding interview, thanks for clarifying this - Python lambda functions in Python is not the simplest one. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically