Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda function

Tags:

python

lambda

What is happening here?

reduce(lambda x,y: x+y, [x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0])

I understand how x is iterating through all of the numbers from 1 to 999 and taking out those that are divisible by 3 or 5, but the 'lambda x,y: x+y' part is stumping me.

like image 920
startuprob Avatar asked Jun 05 '11 14:06

startuprob


People also ask

What is a lambda function in Python?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

What is lambda function in Python give example?

Example of Lambda Function in python Here is an example of lambda function that doubles the input value. In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.

What is the benefit of using lambda in Python?

Lambda functions allow you to create small, single-use functions that can save time and space in your code. They ares also useful when you need to call a function that expects a function as an argument for a callback such as Map() and Filter() .


1 Answers

This is bad Python for

sum(x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0)

It simply sums all numbers in the range 1..999 divisible by 3 or 5.

reduce() applies the given function to the first two items of the iterable, then to the result and the next item of the iterable, and so on. In this example, the function

lambda x, y: x + y

simply adds its operands.

like image 155
Sven Marnach Avatar answered Nov 15 '22 19:11

Sven Marnach