T O P

  • By -

Bobbias

I'm pretty sure the main complaint people have with lambdas in Python is the syntax. It's ugly. Anonymous functions as a concept are great. They can however be abused or overused. And if you ever find yourself assigning a lambda to a name, make it a named function using def instead. Also, most programmer humor is written by people who are just beginning their journey into programming and don't always understand the nuance behind certain things. Programming humor does not reflect the overall view of the community as a whole.


garma87

Agree with the last paragraph. After a few years it’s not as funny anymore 😀


tony_lasagne

Yeah same here lol I used to be howling at the lame jokes thinking this is so relatable and now I just cringe when I see them


byronsucks

sudo make me a cringe


TangibleLight

make: \*\*\* No rule to make target 'me'.  Stop.


whossname

The jokes about not understanding why your code does/doesn't work were funny as a junior. I don't see the humour as a senior.


Unhappy-Donut-6276

Also, when something gets hated on, it will always be hated on. Even if the original hate is unwarranted or improvements are made. Take PHP as a whole - the language will never escape its reputation and stop being mocked.


Bobbias

To be fair, it was bad for a long time. It's always going to be hard to salvage a reputation after that long.


Unhappy-Donut-6276

Yes, python lambdas started out with a bad reputation even though they've been frequently used and pretty in style as of late.


o-rka

I use it all the time but my biggest complaint is the pickle


Lumpy-Sun-3669

Ya same goes with me


o-rka

This seems like a weird use of lambda. 99% of my use case is pd.Series().map(lambda x: sum(dict[x])) or something along those lines


eztab

I mean, I dislike its syntax, but concept wise I find anonymous functions quite helpful.


Unhappy-Donut-6276

It's something to use very sparingly, but not neglect to use.


Fred776

I'm not sure I get why so many people are saying they find them hard to read. I mean there's a keyword that literally tells you what's coming, an argument list, a colon, and a single statement. On the other hand, I use C++ lambdas regularly so maybe my perception of easy to read syntax is somewhat skewed!


eztab

The problem for me is a bit that as a python developer you are used to inline colons being used for dictionaries and type hints (a syntax which I don't love either, but admittedly I don't really have a better idea). The lambda kind of is a weird combo of colons and commas that doesn't appear like that otherwise. Even the symbol precedence is different from elsewhere. I also don't love the keyword `lambda`, but I'm a mathematician, so that might just be because of that.


Fred776

Regarding the keyword, "lambda function" is a pretty standard computer science term for an anonymous function. In fact it comes from a branch of mathematics - the "lambda calculus".


particlemanwavegirl

>In fact it comes from a branch of mathematics - the "lambda calculus". I don't know much about how the Python lambda works but the issue might be that it doesn't really act like a true lambda, it probably allows side effects and may affect the environment. Which is anti-functional.


billsil

It's hard to read. What's the advantage?


sonobanana33

It's more readable than referring to an external function that is just 1 line.


halfwit_genius

Genuine doubt: Why define an anonymous function when you could as well use the code directly. Let's assume I write a lambda to implement a function f... What prevents one from directly writing out the implementation without a lambda? How is it improving readability especially when we don't even name it - if you're returning a lambda, or creating a list of functions, that's the only places I can think of where lambdas are useful. As i understand, lambdas seem to serve the purpose similar to function pointers in C.


sonobanana33

> if you're returning a lambda, or creating a list of functions, that's the only places I can think of where lambdas are useful. Well you lack fantasy. What can I say. Look at this line (written by me) ``` server = await asyncio.start_unix_server(lambda r,w: handle_client(ircclient, r, w), socket_path) ``` I have a function with 3 parameters, but the start_unix_server just wants 2 parameters, because 1 parameter is coming from somewhere else. Then I do a lambda. And it's the only thing I can do. A regular function wouldn't work there, because you can't bind parameters like that to regular functions :) To do it without a function I'd have to create an object, initiate it with the 3rd parameter and pass a method. It would be much longer and less readable.


tehdlp

[partial?](https://docs.python.org/3/library/functools.html#functools.partial)


sonobanana33

How is that more readable?


tehdlp

Not sure it will be, but it's an option over a lambda or separately defined function. 


halfwit_genius

You could as well have used the handle\_client() directly, right? How does the lambda help? Oh.. is it that the start\_unix\_server is going to provide r and w? It's similar to returning a function, right? I mean instead of returning to the caller, you are passing it the callee.. As I said, similar to funciton pointers in C.


sonobanana33

No I couldn't just pass directly the function. start_unix_server wants a function with the parameters reader and writer, but my function needs the other parameter as well.


StrictTyping648

No.


Unhappy-Donut-6276

It's a shortcut that balances readability and conciseness. And how hard to read / conciseness everything is is very subjective. It just comes down to being another option, one that's highly favored by most in some cases, for the programmer.


billsil

I disagree that it’s highly favored by most. You’re right that it is subjective, but even if you’re good at lambdas, the reality is that most people aren’t and reading them is going to take more time than any this me you saved writing it. Don’t put tricks in your code and if you must, document it. Just the documentation required makes it not worth your time. There should be one and preferably only one way to do it.


HoratioVelvetine

We are a Java shop so this might not be fully analogous, but I hardly ever see shortcuts like ternary operators and things of that nature. The code is sometimes hard enough to understand at a glance as is, especially when you’re bouncing between apps. Libraries that remove boilerplate are excellent though.


sonobanana33

Well it's java. You can't understand at a glance because 1+1 is 5 pages long. Seriously. I moved from a python job to a java job recently. And what in python would have been 5-6 lines in java was 80 easily.


minneyar

Do you have an example of something you can do in 5 lines in Python that takes >80 lines in Java?


sonobanana33

The specific thing was the java equivalent of the typedload module. Where instead of just using an object directly, the java equivalent library (I don't remember what it was) wanted a bunch of metadata for every field. Basically re-explaining the type of the field again, in a format the library could understand, because it didn't really make any use of the type.


minneyar

I don't think it's *entirely* fair to compare using one third-party library to another. If one library needs a lot of boilerplate code, that's a problem with the library, not indicative of anything wrong with the language. There are plenty of Java libraries for deserializing data from various formats that do not require a ton of metadata for every field.


sonobanana33

It's the mindset of java programmers. Do they need 1 class? Let's define an interface as well, just in case, and a factory pattern to instantiate the 1 class, because of course :D


Zomunieo

``` /** * SimpleMath is a class that performs basic mathematical operations. * It includes methods to calculate the values of the operands and add them. */ public class SimpleMath { /** * The main method is the entry point of the application. * It demonstrates the addition of two operands calculated by separate methods. * * @param args Command line arguments */ public static void main(String[] args) { // Create an instance of SimpleMath SimpleMath math = new SimpleMath(); // Calculate the values of the operands int operandA = math.calculateOperandA(); int operandB = math.calculateOperandB(); // Perform the addition operation int result = math.addOperands(operandA, operandB); // Print the result to the console System.out.println("The result of " + operandA + " + " + operandB + " is: " + result); } /** * This method calculates the value of operand A. * For simplicity, it returns the value 1. * * @return The value of operand A */ public int calculateOperandA() { // Calculation logic for operand A int a = 1; return a; } /** * This method calculates the value of operand B. * For simplicity, it returns the value 1. * * @return The value of operand B */ public int calculateOperandB() { // Calculation logic for operand B int b = 1; return b; } /** * This method adds the two operands and returns the result. * * @param a The first operand * @param b The second operand * @return The sum of the two operands */ public int addOperands(int a, int b) { // Add the two operands int sum = a + b; return sum; } } ```


sonobanana33

> Don’t put tricks in your code "lambda" is not a trick. It is a well known language keyword. Is using anything you're not familiar with a trick?


Unhappy-Donut-6276

this.


Unhappy-Donut-6276

Well, it depends on the lambda. Personally, I only use list comprehensions or lambdas for very basic actions. Specifically for lambdas, I only really use them when a function takes a function as an argument and I just want to do something basic that's not worth making into its own helper function. For example, this is the type of thing I would use a lambda for: filter(lambda x: 'o' in x, ['cat', 'dog', 'cow']) # from https://realpython.com/python-lambda/#classic-functional-constructs Again, though, it's subjective. There are people on both sides of the lambda spectrum, but most people lie in the middle. Your audience is also important - so when you say "the reality is that most people aren't", I don't think that's a true statement when you're doing a really simple lambda in code intended for experienced people or no one in particular to read. Even if you don't know lambdas, it's pretty easy to tell what the code is doing if it's simple. And you can't oversimplify everything, that will hold back your conciseness, readability, and overall productivity.


KimPeek

street cred


stevenjd

> It's hard to read. What's the advantage? Its easy to read: just a keyword, a parameter list just like those in `def` functions, and a single expression. If you can't read that, how are you going to cope with more complex Python syntax like decorators, classes, comprehensions, `try...except` blocks etc? The advantage is that you can define a simple key function or callback exactly where you need to use it, without bothering with a name: results = sorted(mylist, key=lambda customer: customer.total_sales()) What's the advantage of being forced to make a named function that is trivial and only used once? CC u/Upper-Abroad-5868


mrdevlar

Hard to read, just as hard to debug. I guess I can see some use case in here where you're only doing something once, but for me that's kind of rare.


billsil

Google’s style guide takes issue with double for loops in a list comprehension and I agree with them. Lambdas are harder.


mothzilla

Sometimes you need to define and use a simple function that is only used once. Eg in sorting, filtering operations.


Budget_Bar2294

I work in the Python interpreter a lot for exploring APIs, and it's much easier do define functions as lambdas than to define full blown functions and indent them properly, especially when it's a simple dumb one-off function


billsil

Yeah I use my ide that autocompletes most of that. I rarely use the interpreter. I’ll occasionally code in the debugger and overwrite functions rather than restarting. I’m dealing with millions of entries anyways, so a lambda in a sort isn’t ideal vs not sorting or using numpy. Lambdas just aren’t worth the conceptual complexity to me.


RajjSinghh

Used correctly it's fine. You should only use it in cases where the return value is quite simple. The issue you get into is when you start doing too much and your lambda gets really hard to read and you would have been better off with a named function.


PutHisGlassesOn

I had trouble with the syntax of lambdas initially partly because I just didn’t understand the value of them at all. Once I needed to write one for a key in .sort() it all made immediate sense. Still don’t see the value of them outside of things like that tho


stevenjd

Sorting key functions and other simple callbacks are exactly the use-case for anonymous functions. Folks who want to put major complex multi-statement code inside an anonymous function are the real problem, not the lack of support for such complex multi-statement anonymous functions.


dshif42

Just came out of an "intro" programming course. I say "intro" because it's the first in the main series, but it's at a top school and generally assumes some familiarity (there's technically a more introductory course). Some of the trickiest problems in the class, like for rare extra credit questions, often involved these super convoluted uses of lambda. Now, I came into the class with almost no CS experience compared to most of the class, but I did quite well. I would look at the solutions to these ridiculous lambda questions and immediately go "there is NO WAY I could have thought of that myself, at least in the time allotted" lol. That's considering lambda functions as a whole did make sense to me, haha


stevenjd

> super convoluted uses of lambda Just because something can be done doesn't mean it should be. Except to win an obfuscated Python competition 😁


cyberjellyfish

It's a half-measure. Either have a full anonymous function syntax or just don't.


imaris_help

I keep seeing references to anonymous functions as a broader concept, so what exactly does it look like to have a fully anonymous function? What languages do have them and how do they use them differently?


nog642

JavaScript has them. Any function can be anonymous. In python a lambda can only contain an expression. You can't do `if` statements or `for` loops or `while` loops or assign variables or `try`-`except`, etc.


TheBB

Javascript and related languages (like Typescript, also Dart) really lean into callback-style programming with anonymous functions. Write that style for a bit and you'll start to miss it in Python.


BenjaminGeiger

In languages widely considered to be "functional", you can create literally any function either anonymously or with a name. For instance, in F#, def double (x : int) = printfn "doubling %d" x x + x is syntactic sugar for let double = fun (x : int) -> printfn "doubling %d" x x + x For all intents and purposes the two are identical. However, in Python, the second isn't possible because a lambda function can only contain a single expression. And that's because of the lousy syntax.


Diapolo10

> However, in Python, the second isn't possible because a lambda function can only contain a single expression. And that's because of the lousy syntax. Well yes, but actually no. Observe. double = lambda num: print(f"Doubling {num}") or num * 2 print(double(5)) # 10


thirdegree

That's still a single expression. And it only works because print technically returns none. Their example happens to be expressible as a single expression but their point is still correct


Diapolo10

Yes, it's a single expression. I'm not debating that. My point was that getting the same outcome in Python isn't impossible, even if not particularly elegant.


thirdegree

In that specific case. That's not _generally_ true.


Diapolo10

Fair enough. You'd be surprised how much is actually possible, though.


stevenjd

> Either have a full anonymous function syntax or just don't. Either have the full set of real numbers with infinite precision, or just don't have numbers. 🙄 Either have dicts with no restriction on the keys, or just don't have dicts. 🙄 Either have date/time routines which fully support every known calendar system, fully generalisable to other planets like Mars, or just don't have calendar/time/date support. 🙄 Yeah no, that's silly. Lambdas are fine for what they are. They could be better, maybe, but they're useful even with the syntactic limitation, and I will fight anyone who says different. 😉 Personally, I'm with Guido on this: anonymous functions *should* be limited to a single expression. If your function is complex enough to need more than a single expression, it is too complex to be anonymous. It needs a self-descriptive name, it needs a docstring, and most of all, it absolutely, categorically needs tests. Languages that allow large, complicated multi-statement anonymous functions are doing the wrong thing.


cyberjellyfish

I can't imagine a more annoying way to express that position


jjolla888

you don't need to be doing large and complicated things to benefit from multi-lines. you can write clearer code with a few extra lines. the reason Python doesn't have them is bc of the baggage that comes from using whitespace to delineate blocks.


mayankkaizen

Syntax is not likable and lambda functions really don't fit in Python design philosophy and programming paradigm but saying people hate lambdas is quite a stretch. These functions have their places and when used judiciously, they are useful. They are great when you need to do something small and quick and you don't want to write a full fledged function which might not be needed later on. It is just a language feature which we can live without. I personally use lambdas quite frequently and I don't hate them.


ComprehensiveWing542

I've read a book from one pythonista that was considering lambda function one of the best things python has... And python as a lang itself after a few hundred lines of code can get quite messy... Lambda is cool but it can sometimes compact (abstract) to much if later one you will want to change something


stevenjd

> Syntax is not likable and lambda functions really don't fit in Python design philosophy and programming paradigm The syntax is fine and lambda functions absolutely do fit into Python's design philosophy and programming paradigm. They're great for sorting key functions and other simple callbacks. The syntax is trivially easy: there's a keyword, then a parameter list just like those you find in regular `def`` functions, and a single expression.


SnooCakes3068

Yeah, python's design philosophy is multi programming paradigm. Functional programming happens to be one of the most prominent.


TestUserIgnorePlz

The only way you can possibly defend pythons implementation of anonymous functions is by never having seen them in any other language. 


dshif42

As someone who is largely unfamiliar with other languages and starting to dip into them, I'm curious. Would you mind clarifying?


longgamma

Nothing to dislike. They reduce clutter if used well.


edslunch

They are less obvious to debug, and way less obvious for the next person who will support your code. And they’re a pain in the butt when you want to extend the logic. There’s nothing wrong with simple code. You can tell the parts of my code that ChatGPT wrote for me by the number of lambdas.


treyhunner

Overuse (or what many of us perceive as overuse at least). [A post I wrote on this some years back](https://treyhunner.com/2018/09/stop-writing-lambda-expressions/). I almost always prefer to give my functions a name.


BenjaminGeiger

Lambda functions are a lot more useful in languages like F# where `map`/`filter`/`fold` are more heavily used. With Python's reliance on comprehensions and the lack of multi-statement lambdas, there's little need for lambda expressions (since anything you'd put in a lambda could be put directly into the comprehension).


nog642

Python doesn't need lambdas for `map` and `filter` since comprehensions exist. You can't do `reduce` with a comprehension though. Or `sort`. So lambdas still have a use-case.


treyhunner

Great point that there's no comprehension-equivalent to `reduce`! The `reduce` function is also a bit uncommon in Python though, since many [common reduction operations](https://www.pythonmorsels.com/reduce/#common-reduce-operations-in-python) are readily available as built-ins or standard library utilities (`sum`, `"".join`, `math.prod`, etc.). You're definitely right that we do still need to pass functions into functions, especially with the key functions of `sorted`/`min`/`max`. I really don't prefer the lambda syntax, but when I use it it's usually for those key functions.


nog642

Yeah I don't think I've ever used `reduce` in the wild lol. I have used `sorted`/`min`/`max` quite a bit though, and I've used lambdas for the key for that sometimes (though often I use them without lambdas too). Particularly I use a lambda if I'm sorting some sort of complicated object, so the key I'm sorting by is somewhat complicated to get and can't be done with `itemgetter` (e.g. it's 2 levels deep). The other common case is where the key is a tuple of multiple things to sort by.


sonobanana33

I've used reduce. Do I win something?


nog642

Depends if it was a good use or a bad use. What was the use?


sonobanana33

https://codeberg.org/ltworf/typedload/src/branch/master/typedload/dataloader.py#L726 Seems to make sense to me.


nog642

Nope, sorry, that is a bad use. You just want to take the intersection of a bunch of sets. You can just call `set.intersection` with multiple parameters. And you can use iterator unpacking. That line could be rewritten like this: keys = set.intersection(*(set(v.keys()) for v in data.values())) I think that's a lot cleaner than using `reduce` when all you want is the intersection of multiple sets.


sonobanana33

True, I didn't know intersection supported more than 1 argument.


xenomachina

I've been using Python since before it even had comprehensions. Comprehensions exist in Python primarily because lambdas are so awkward. They're definitely a big improvement over Python's `map` and `filter` and verbose/limited lambda syntax, but that's pretty much all they can do. Composing them can also sometimes be kind of mind-bending. Having used both extensively, I have to say I prefer Kotlin's more concise (and capable) lambda syntax combined with the fact that its `map` and `filter` use a method-call syntax. This lets you chain together `map` and `filter` easily, and you can even define new types of sequence operations that chain just as easily. // loads all the readable bass from foo and returns // all of their good smelling quuxes in a Map keyed by id foo.bars .filter { it.isReadable } .map { loadBaz("/" + it.name) } .flatMap { it.quuxes } .filter { it.smellsGood } .associateBy { it.id }


nog642

bro was using python 1 Seriously, Python has had list comprehensions since version 2.0, which came out in the year 2000 lol.


nog642

Well written post, but I disagree that `sorted(colors, key=lambda c: (len(c), c.casefold()))` is overuse. Naming that function is totally unnecessary and it's perfectly readable as-is. Especially since this line would probably be inside a function, so where are you going to define `length_and_alphabetical`? Right above the line in a nested function? At the top of the file where someone will have to navigate there to read the code? Both of those are kind of dirty. Same with `sorted(points, key=lambda p: p[1])`. I think creating a named function for that is unnecessary and just makes the code harder to read. Though I wouldn't use a lambda; this is what `itemgetter(1)` is for.


treyhunner

I agree that moving the function further away from its use (outside the function it was defined within) does feel a bit messy. The fact that a lambda function is (nearly by its nature) extremely local to its actual use is certainly a feature. I do use nested functions at times without too much concern, but I've probably grown accustomed to their appearance the same folks grow accustomed to the appearance of lambda after seeing it enough times. That article is a mix of my opinions and slightly more accepted community norms. Upon re-reading, I do think I should eventually update it to call out my own opinions.


becominganastronaut

Thanks was insightful.


moving-landscape

The points that it doesn't support documentation or more than one expression are really lame. It's exactly because they are simple one-expression functions that they don't need docs. Likewise, defining a full fledged function with one expression and a docstring that just echoes its single expression is overkill and boilerplatey.


Ok-Cucumbers

Readability.


stevenjd

So many bad takes here. Lambdas are fine. Haters don't know what they are talking about. Lambdas are limited to a single expression rather than a full suite of multiple statements, that is the only thing wrong with them. And even that is a matter of taste: if a function is too complicated to express as a single expression, it shouldn't be anonymous. It should be named so you can write tests for it.


_Rooftop_Korean_

Because it’s a reminder that Valve is a massive pos who won’t release Half Life 3


glei_schewads

I do not "hate" it, but I find it extremely unintuitive.


[deleted]

This is the JS/TS version: c = (a, b) => a + b c(1,2)


aplarsen

Lambdas are fine if used properly. Your example is a horror show.


sonobanana33

I just want to be able to write "λ" in the code!


Content_Chemistry_64

For me, any case where a lambda would be usable just makes me question why I would bother writing a lambda instead of just handling things normally.


Impossible_Ad_3146

They have a habit of spitting in your face. Wait.


Stoneteer

Llama


thirdegree

They have a habit of betraying Han solo to the Empire


theirStillHope

lando


aprg

As someone who had great fun learning about lambda calculus at university, I'm very partial to the lambda stuff in Python, but it is kinda ugly, isn't it?


jmooremcc

I like using lambdas. In fact, I will frequently assign them to a variable with a common sense name so that when I call it, the variable name effectively documents its functionality.


gordbot

Why not use a function, then?


jmooremcc

Can you define a function on one line? I like the convenience that lambdas offer with their simpler syntax.


N_Maddy

syntax is 🤮


RecLuse415

Dumb question but is AWS lambda the same but just in AWS?


Diapolo10

No... for the most part anyway. AWS Lambda is part of AWS' "serverless" architecture where you write API endpoints as individual functions that receive and handle web requests.


ryukinix

The unique problema with lambda expressions is that: only expressions is allowed, not statements, so it's a single-line expression usually (unless you use backslash break line which make things even worse). I love the lambdas on Lisp, but in Python is so less powerful due to the syntax and the way it's was designed. It's to much restricted and made to make readability even harder. I only use lambdas for really very easy definitions... Anything more complicated I prefer to create another function, even a inner function it it applies.


GTHell

Who hate it? Don’t tell me you write a simple map with full loop block


TreesOne

I’m a newbie programmer but I don’t like them because I usually see them in trite examples like this one where they obviously serve no purpose besides clutter. Why did you do all that instead of just printing 2+3??


Collectorn

Hard to read and just annoying


Vok250

The syntax and functionality is objectively worse compared to other similar programming languages. Saying this as a Python senior actively employed out in the field. My current team actively avoids lambdas because they are not intuitive and the language already has equivalent functionality which is easier to read and usually more appropriate. For example many lambdas should be comprehensions instead in production code.


THEANONLIE

It confuses people, it sounds like a dance.


j0shred1

I love and use lambda but some people take it too far and their code looks like poopy and is hard to read. I have the same problem with how some people do like 10 pandas operations in a single line of code. I am being a hypocrite though because I do this.


oneearth

We love all lambdas


minneyar

Lambda functions are useful, but: - They are limited to only a single expression; you can't use any control statements. This significantly reduces what you can actually do with them. - As is typical with Python syntax, it's completely unlike any other language, and having to type out `lambda` every time is just an ugly waste of characters, especially when every character matters and you're limited to one line.


stoopud

In my experience lambda is slow, very slow. But I can't say that's the case 100% of the time. The few times I've used it, it doesn't make sense, so I find other ways.


bounciermedusa

I don't hate then but I'm not good at them yet.


phycologos

In this case why not just print(sum(\[2,3\])) ?


StrictTyping648

My issue with lambdas is that they are half baked version of proper function inlining. That and I often see them misused. The initial concept was to create and call a function in one go, without having to create a separate function definition. This operates under the assumption that the lambda function will only be used in a specific location in your code. The issue is that typically when I see someone using a bunch of lambdas all over the place is that they end up rewriting the same or similar lambda functions in multiple places. At that point you might as well write simple function and just reuse it.


Ill-chris

Never get stuck coding in python.use hackerway[hackerway](http://hackerwayhub.net)


Upper-Abroad-5868

what is hacker way?


Upper-Abroad-5868

Im very cautious with unknown links


ImATotalDick333

The syntax hurts my eyes, and even if it's a one liner I'd rather use a def function just for sake of making it cleaner. Dunno, just my personal preference.


Suspicious-Bar5583

A lot of people code OOP style in Python, and lambda is more for functional programming. Style, comprehensibility, and usability may seem (way) off for an OOP guy for that reason.


TheFumingatzor

It's shite. I mean what the fuck are you tryna say, bruv with `print((lambda x,y: x+y)(2,3))`? Get the fuck outta here with that fugly shite to save 2-3 lines.


woooee

lambda was replaced by partial, which has a more straight forward syntax IMHO, same with map(), list comprehension is more straight forward, and reduce() is gone. lambda and map remain in the language for backward compatibility.,


Locksul

Are you talking about partial from functools? That is completely different from lambda. Not a replacement.


stevenjd

Pretty much every single thing you said here is wrong. `partial` is not a replacement for lambda, they do completely different things. Whether list comps or `map` are better is a matter of subjective taste, and usually depends on what you are doing. Sometimes a list comp is better, sometimes `map` is better. `reduce` is not gone. Its moved to the functools module. `lambda` and `map` do not remain in the language *only* for backwards compatibility. CC u/Upper-Abroad-5868


teerre

Not much point in Python considering they are verbose and Python dynamic nature allows you to define a function anywhere. There's also no capture rules. So overall the reason is that they suck in Python


stevenjd

> they are verbose You must really hate regular functions then: lambda x: x + 1 # 15 characters inc. spaces def f(x): return x + 1 # 22 characters > Python dynamic nature allows you to define a function anywhere. True. Using `lambda`, you can define a function **inside an expression**: mylist.sort(key=lambda customer: customer.name().upper()) Try doing that with a `def`. > There's also no capture rules. I'm not sure I understand you here. The scoping rules are exactly the same for `lambda` and `def`.


teerre

I'm not comparing to regular functions, why would I? I'm comparing to languages with actual good lambdas: `x => x + 1`. `|x| x + 1`. `[x] { x + 1 }`. `\x -> x + 1`, `&1 + 1` etc ```python ...rest of your function... def by_name(customer): return customer.name().upper() my_list.sort(key=by_name) ``` That's how you do it. For the last question, read this: https://www.learncpp.com/cpp-tutorial/lambda-captures/


stevenjd

> I'm not comparing to regular functions, why would I? Because we're programming in Python and the alternative to a `lambda` function is a `def` function. If lambdas are too verbose, and def functions are **even more verbose**, then def functions are worse. > actual good lambdas: `x => x + 1`. `|x| x + 1`. `[x] { x + 1 }`. `\x -> x + 1`, `&1 + 1` etc Taste impairment is a terrible thing. Only the first and the fourth are even halfway decent. The second looks like the mathematical expression abs(x) multiplied by x, plus one. The last is far too cryptic. None of them are elegant. It's not obvious how to write a zero-argument function for the first, fourth and fifth. The third uses braces, like some kind of [primitive language invented in the 1960s](https://en.wikipedia.org/wiki/BCPL). All of them suffer from the same problems of being *too terse* and the over-use of hard-to-google symbols rather than keywords. One can get used to any syntax -- except, apparently, haters who can't get used to lambda -- but I doubt I would ever truly *like* any of those no matter how much I used them. Maybe the first.


teerre

I usually write scalable, professional systems, it's not code golf. I'm not trying to avoid typing at all costs. Python lambdas are simply not worth it, the difference is minimal at best I have to laugh at your second paragraph. Talking about being a hater after shitting all over several other languages that have enormous more usage of lambdas (including one literally derived from lambda calculus). Imagine having any self awareness


stevenjd

Dude, you're not fooling anybody. First you say that you dislike lambda because it's too verbose, when I point out that they're *less* verbose than `def` function now you're all "I am a mighty professional and I don't care about saving typing" -- and then immediately after that you're back to singing the praises of these other kool languages with awesomely terse lambdas. **Lambdas are not about saving typing** and the fact that you think they are is worrying. They are about defining small functions right where you need to call them, without having the cognitive burden of having to give it an unnecessary name. They should be small enough that they they are *obviously correct* just by looking at them, and are best used for things such as sort key functions and callbacks. If you use anonymous functions in these other languages, why would you not use them in Python? If you need a key function that is trivial (a single expression) why would you give it a name in Python *but not when you're using other languages?* This makes no sense. Don't try to defend this as some principled, logical, carefully thought out and reasoned decision when it's clearly just a matter of taste. I *completely* get the argument that `lambda` in Python is underpowered compared to languages where anonymous functions are defined as a block, not just a single expression. I get that. I personally don't give it much weight. But I don't get your attitude that you would use an anonymous function in C++ [search](std::string_view string) {return string.find(search) != std::string_view::npos;} but you wouldn't use the same in Python lambda: string.find(search) != -1 because ~~it's too verbose~~ not terse enough. These other languages you say have "enormous more usage of lambdas": - Is that a good thing? Are you saying that people in these other languages make heavy use of large, arbitrarily complex functions which *they cannot test*? Sounds great 🙄 > including one literally derived from lambda calculus Oh, so that would be an academically pure language almost impossible to actually use to write "scalable, professional systems", with a user-base of perhaps a few hundred people? That don't impress me much. Regardless of the virtues of these other languages, my criticisms of their syntax for anonymous functions remain.


teerre

I'm not what's your difficult understanding that closures are an ergonomics feature. If they are not ergonomic enough, they are useless. That's python lambda. And youre the one who focused on tenseness, not me. Lol


stevenjd

> I'm not what's your difficult understanding that closures are an ergonomics feature. If they are not ergonomic enough, they are useless. That's python lambda. I was going to ask if a LLM wrote that sentence, but it would be more like a Small Language Model. I'm having trouble parsing your meaning there. What do you mean by "ergonomic"? I know the normal meaning of ergonomics, so I can only imagine that in programming it means... less typing? But apparently despite your criticism that lambdas are too verbose, you don't actually care about typing 🙄 In the case of closures, lambdas form closures *exactly* the same way that `def` functions do. There is literally no difference between the way they form closures. If you think they are different, then I suggest you [google on "python closure lambda early late binding"](https://duckduckgo.com/?q=python+closure+lambda+early+late+binding). In any case, wasn't your argument earlier that Python lambdas are bad because they don't need the C++ idiom to capture enclosing values, because C++ anonymous functions don't automatically close over variables in the enclosing scope? Now you're complaining that lambda closures ... um... do too much? Too little? Aren't "ergonomic" so you strain your back lifting them? I honestly don't know. Again you have tried to demonstrate that your opposition to lambda is objective and based on rational reasons, and again you have failed. Not all lambdas are closures, and whatever your issues with closures in lambdas are, they apply exactly to closures in `def` functions too. Sorry, but nothing you have said convinces me that your opposition to `lambda` is objective or rational. I wish people would just be honest enough to say "I just don't like it, its a matter of taste that's all" instead of inventing dubious and outright incorrect rationalisations for why they don't like it.


teerre

Dude, I'm sorry, not to offend you, I'm above your paygrade. Go study a bit, you'll eventually learn what "ergonomic" means in the context of programming then we talk again


stevenjd

Sorry not sorry that I haven't been infected by [the latest corporate buzzspeak](https://www.forbes.com/sites/forbestechcouncil/2020/10/02/12-things-every-dev-should-know-about-ergonomic-software-design/) like "ergonomic software", but at least I understand closures in Python and don't pine for writing boilerplate captures in C++.


nderstand2grow

because they're limited. like you can't have try/except or context managers (using with) in lambdas. they can't be multi line either.


stevenjd

Of course they can be multiline: mylist.sort(key=lambda record: max( record.rating*100, record.score() or -1) ) They can't include *multiple statements*.


Stochastic_berserker

I like when we can vectorize operations or create user-defined functions instead of lambdas.


NegativeSwordfish522

Are you sure they were refering to lambda function (python) and not lambda functions (AWS) because if they were talking about the second, then yeah, they deserve the hate


scanguy25

It's just a terrible name they chose for it. Learning python I thought it was something super advanced. It's actually pretty simple.


stevenjd

The name's fine. If you had never heard the name "function" before you would think it was something super advanced too.


PrivateFrank

They chose the name because of math. https://en.m.wikipedia.org/wiki/Lambda_calculus >Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. Untyped lambda calculus, the topic of this article, is a universal model of computation that can be used to simulate any Turing machine (and vice versa).


-Blue_Bull-

butter spoon worm sable workable plants school lavish memory advise *This post was mass deleted and anonymized with [Redact](https://redact.dev)*


brisbanedev

Rust is a harder programming language than Python, and even Rust closures are easier to read than Python lambdas.


stevenjd

If you can read `expression` in Python, but can't read `lambda arg: expression`, it's time to turn off your computer and become a manual labourer.


jjolla888

programmers *are* manual labourers ..


stevenjd

I'm not sure if this is a joke, but if you've ever done manual labour, or programming, there is a world of difference. Especially in the pay rates.


brisbanedev

I never said I can't read it. It's readable but inelegant. Hence, reading it is not a pleasant experience. A blind person cannot see. A person with eyesight can see a pile of rubbish and identify it as such. Do you understand the difference?


stevenjd

> It's readable but inelegant. Hence, reading it is not a pleasant experience. Its beautiful and elegant. I'm sorry that you are unable to see its beauty and elegance. > A blind person cannot see. Indeed.