Henry Lee
Henry Lee

Reputation: 831

Differences between functions and lambda and when to use which in Python 3

I'm pretty new to Python (and programming in general). I was wondering, since lambda and functions are very similar, when is it proper to use which and what are the differences between them?

The reason I'm asking is I've only seen lambda used for very basic and simple programs, such as:

sq = lambda x: x**2 
print(sq(25))

While functions can be much more complicated like having multiple parameters, different looping types, if/else, recursive, calling another function (composition, I think), etc.

I know you can call a function inside a lambda like:

def turnUppercase(n):
    return n.upper()

a = lambda x: turnUppercase(x)
print(a('Cookie'))

That example is pointless, but still... I've never tested the limits of lambda by trying other things.

What are the limits of lambda? How can you extend the functionalities of lambdas (if only to impress people) to match that of functions? (Calling a function inside lambda, calling another lambda, loops inside, and so on).

Note I'm asking about Python 3.

Thanks!

Upvotes: 1

Views: 1537

Answers (1)

NightShadeQueen
NightShadeQueen

Reputation: 3334

A lambda is a nameless function. In python, it has to fit in one line. It's mostly useful only when you're calling a function that takes another function as an argument.

Example:

listOfLists.sort(key=lambda x:x[1]) #Sort list of lists by second element

(see sorting: Key Functions. Probably the most common valid use of lambdas)

You can do a lot of stupid stuff in lambdas (check out any code golf written in python) but it's generally recommended to keep them simple if you're going to use them in Actually Maintained Code.

While functions can be much more complicated like having multiple parameters, different looping types, if/else, recursive, calling another function (composition, I think), etc.

Incidentally, I think the only one of these you can't do in a lambda is recursion.

Multiple parameters: lambda x,y: x**2+y**2

Loops (technically): lambda x: [subprocess.call('pip install --upgrade ' + dist.project_name, shell=True) for dist in pip.get_installed_distributions()] (and yes I know I'm a horrible person)

If/else: lambda x: "Blue" if x > 1000 else "Orange"

And as for what you can't do in lambdas...uh, keyword arguments? *args? Any bit of complexity without your code looking like a drunk cat wandered by and hit parens, square brackets and curly brackets randomly?

I think the general rule of "If your boss came up to you and asked the question 'Why is this a lambda' and you can answer immediately AND explain what the lambda does, you might be justified in using a lambda. Otherwise, it's better to err on the side of not using one."

Upvotes: 2

Related Questions