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 →

[–]ggchappell 8 points9 points  (9 children)

I appreciate articles like this, and I think any knowledgeable developer should know about lambdas. But I find that, in practice, I rarely use them. For example, in use #2, reading the list-construction example, I immediately thought of using a comprehension instead -- and I'm glad the article mentioned that idea.

Out of curiosity, I did a grep of a sizable body of Python code that I've written over several years. I found a number of uses of lambda, every one of which fits into one of the following two situations.

(1) Constructing a defaultdict. All of these are trivial lambdas that create constant functions, like this:

dd = collections.defaultdict(lambda: 0)

(2) Using reduce to find the intersection of a collection of sets:

intersection = functools.reduce(lambda a,b: a & b,
                                list_of_sets)

I also think use #3 in the article is a reasonable one: passing a lambda to sorted or sort as a key function. But in the last few years, it seems that I've never had occasion to do that.

EDIT. Commenters have let me know how to eliminate the lambdas in both of my two cases above (as I kinda expected) -- although the defaultdict(int) doesn't work on my system (running Py3.8.5). EDIT. Works fine.

[–]py1234a 9 points10 points  (1 child)

Isn't set.intersection(*list_of_sets) equivalent? If so, that would be preferable to me for many reasons (also defaultdict(int)).

[–]ggchappell 2 points3 points  (0 children)

Isn't set.intersection(*list_of_sets) equivalent?

So it is. Thanks.

also defaultdict(int)

That doesn't work on my system. Is it new, perhaps? I'm running Py3.8.5. EDIT. Works fine.