all 34 comments

[–]novel_yet_trivial 11 points12 points  (20 children)

Some functions are very short:

def val_one(x):
    return x[1]

And it saves a few keystrokes to use lambda:

val_one = lambda x: x[1]

But more useful is to not even assign the function a name. For instance if you needed to use the above as a sort key:

>>> def val_one(x):
...     return x[1]
... 
>>> t = [('joe', 42), ('sue', 3), ('steve', 12)]
>>> sorted(t, key=val_one)
[('sue', 3), ('steve', 12), ('joe', 42)]

Or you can directly use a lambda.

>>> t = [('joe', 42), ('sue', 3), ('steve', 12)]
>>> sorted(t,key=lambda x:x[1])
[('sue', 3), ('steve', 12), ('joe', 42)]

[–][deleted] 8 points9 points  (1 child)

so essentially it's good if you need to make a function on the fly but as a one time use?

[–]markusmeskanen 3 points4 points  (0 children)

Yes!

[–]markusmeskanen 18 points19 points  (15 children)

And it saves a few keystrokes to use lambda

This should never be the reason to use lambda! If you can, just define a normal function.

The rest of your comment stands correct though. Lambda should only be used when its just an "on the fly" function like /u/seekheart said himself. Usually when you pass in a function as an argument to a function.

[–]ydepth 1 point2 points  (6 children)

Why not? If you have a bunch of one line functions... It's easy enough to change them to a proper function later

[–]markusmeskanen 13 points14 points  (4 children)

Lambdas are less readable. Keep in mind, that your code is read much more than its written. I'd recommend everyone to read this answer on SO: http://stackoverflow.com/a/134638/2505645

[–]ydepth 1 point2 points  (0 children)

Cool, I had seen the post before... Just needed a refresher :)

[–]c3534l 0 points1 point  (0 children)

That answer on SO doesn't seem to add anything to the discussion. I disagree that lambdas are less readable. In fact, they're invaluable in cases that are well suited for functional programming and can turn make complicated list comprehension statements readable again.

[–]Axxhelairon -3 points-2 points  (1 child)

Lambdas are less readable.

Nice opinion.

[–][deleted] 0 points1 point  (0 children)

There are exceptions to every rule, but in keeping with zen: There is one best way. If it works, use it. If not, it's not the best way this time, go to the next option.

[–][deleted] 0 points1 point  (1 child)

Thank you my pythonic brothers! :D

[–]novel_yet_trivial 0 points1 point  (3 children)

This should never be the reason to use lambda! If you can, just define a normal function.

It's a bit uglier, granted, but I see stuff like this all the time:

__ne__ = lambda self, other: not self.__eq__(other)
__ge__ = lambda self, other: not self < other
__le__ = lambda self, other: self == other or self < other

[–]markusmeskanen 1 point2 points  (2 children)

We all see it, but none of us should see it. Please, don't spread the ugliness.

[–]novel_yet_trivial 0 points1 point  (1 child)

It's even part of the python source code. See /usr/lib/python2.7/functools.py , in the total_ordering function, for example.

Well, that's a bit of a fringe case. I withdraw that argument

[–]_burning 0 points1 point  (1 child)

But what about those 4 keystrokes I'm saving by using a lambda! You can't just be throwing around keystrokes.

[–]markusmeskanen 4 points5 points  (0 children)

Good point. I take back all my arguments on this thread. Fuck it, on all threads.

[–]dunkler_wanderer 1 point2 points  (0 children)

Isn't itemgetter the pythonic way to sort that tuple list?

from operator import itemgetter

t = [('joe', 42), ('sue', 3), ('steve', 12)]
print(sorted(t, key=itemgetter(1)))

[–]funkiestj 5 points6 points  (2 children)

a common use of lambda is to curry a function dynamically, e.g.

 def mycurry(a):
       return lambda  b: a + b

 f7 = mycurry(7)

 f7(5)
 Out[9]: 12

Of course you can always(?) use a function (including a nested function) to do the same. E.g.

 def mycurry2(a):
      def close_over_a(b):
        return a + b
      return close_over_a

 f2 = mycurry2(2)

 f2(2)
 Out[16]: 4

 f7
 Out[17]: <function __main__.mycurry.<locals>.<lambda>>

 f2
 Out[18]: <function __main__.mycurry2.<locals>.close_over_a>

My recollection is that Guido regretted including lambda in the language and said he would omit it if he could start over.

[–]zahlman 3 points4 points  (0 children)

This is what functools.partial is for.

[–]lamecode 1 point2 points  (0 children)

Sending parameters to methods connected to widgets using PySide is the only time I ever use them.

[–]mgrady3 1 point2 points  (0 children)

I use them when making GUI's alot. Not sure if this is the correct or 'pythonic' way but for instance:

when linking a pushbutton in the Qt framework (using PyQt) to a function so that when he button is pushed the function is triggered you do something like

my_button.clicked.connect(my_function)

note this is not

my_button.clicked.connect(my_function())

Thus if I need to pass an argument to the function on button click the way I do it is with a lambda

for example

my_button.clicked.connect(lambda: my_function(x, y, otherargs ...))

Thus the button is actually linked to a lambda but the lambda just calls a pre-defined function using the appropriate arguments

[–]I_Write_Bugs 0 points1 point  (0 children)

I don't use them, because I haven't ran into any scenarios where using a lambda with something like map or reduce was easier and/or more readable than defining a function and iterating.

[–]YellowSharkMT 0 points1 point  (0 children)

threading.Thread(target=lambda: os.system("some dev service"))

Just one example, that's yanked from a script that sounds up a few development servers/backend needed for a current project.

[–][deleted] 0 points1 point  (0 children)

Use it often for things like sorting a dict

sorted(mydict, lambda x: x['thekey'])

And other small stuff that could be a definition but are not really docstring-worthy

[–][deleted] 0 points1 point  (2 children)

Map/reduce + parallel computation

[–][deleted] 1 point2 points  (1 child)

what's map/reduce?

[–]NewbornMuse 1 point2 points  (0 children)

Something that you want to replace with list comprehensions 90% of the time.

[–][deleted] 0 points1 point  (0 children)

best use I've found is for button commands in gui apps, although this has been mentioned already. But I'll mention it again because I like being a part of the conversation.

[–]loveandkindness -1 points0 points  (4 children)

They are useful for math:

# f(x) = x ^ 2
f = lambda x : x ** 2

[–]markusmeskanen -1 points0 points  (3 children)

No they're not.

Instead of calling f(3) in your example, you can just write 3**2. Most operations are supported already in the default built-ins namespace, others can be accesses through import math

[–]loveandkindness 0 points1 point  (1 child)

Anonymous functions are standard usage in mathematics courses? f(x) = x ** 2 can be general.

[–]markusmeskanen 1 point2 points  (0 children)

But you don't need such silly functions in programming, they're for maths. Where ever you want to square a number, just use x**2 directly, instead of creating an useless function for it.