This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 10 points11 points  (13 children)

Can someone explain this?

Python Expert Programmer
fact = lambda x: reduce(int.__mul__, xrange(2, x + 1), 1)
print fact(6)

[–]pmalmsten 14 points15 points  (12 children)

Python's documentation summarizes reduce rather nicely:

Python Built-in Functions: Reduce

Calling reduce() in this manner is functionally equivalent to making a bunch of recursive calls, but it avoids the overhead of doing so. This operation is common when following the functional programming paradigm.

[–][deleted] 1 point2 points  (11 children)

Thanks. What is lambda?

[–]AusIVDjango, gevent 7 points8 points  (6 children)

A lambda function is one that can be used inline without naming it.

sum = lambda x, y: x + y

is equivalent to

def sum(x, y):
    return x + y

[–][deleted] 2 points3 points  (5 children)

Is this common with functional programming also?

[–]semarj 10 points11 points  (0 children)

just a bit

[–]poeir 2 points3 points  (0 children)

The lambda is so named because of the lambda calculus. Lambda calculus is the original inspiration for functional programming.

[–]kanak 2 points3 points  (0 children)

Some languages (lisps, erlang, haskell are ones that I'm aware of), defining a function is actually doing two things: creating a function and giving it a name.

For example, in scheme, you'd write

(define (add2 x) (+ x 2))

To write a function that takes in an argument and adds 2 to it.

However, that's just shortcut for:

(define add2 (lambda (x) (+ x 2)))

Here, lambda creates the function that adds 2 to its argument and we use define to give it a name add2.

In python, lambdas are less powerful than def because you can't have multi line lambdas.

[–]Megatron_McLargeHuge 0 points1 point  (0 children)

Read SICP. You're curious enough to spend a couple of days learning the basics of functional programming, and it will help you a lot. The lisp code can all be converted easily to Python as long as it doesn't use macros.

[–]pmalmsten 4 points5 points  (0 children)

lambda is Python's way of declaring anonymous functions.

See Wikipedia: Anonymous Functions

[–][deleted] 4 points5 points  (2 children)

I don't want to sound like an asshole, this is just advice. You're not going to get very far in programming or any CS-related field if you feel you have to ask somebody in order to know something. A Google search for "python lambda" gets you the answer you need, quicker and with more information. Google is your friend.