JoshNahum
JoshNahum

Reputation: 133

Equivalent to Lambda Expressions in Python

A common operation I perform is joining a list of lists of letters into a list of words (strings).

I normally use a list comprehension:

lists_of_letters = [["m", "y"], ["d", "o", "g"], ["s", "k", "i", "p"]]
list_of_words = ["".join(a_list_of_letters) for a_list_of_letters in lists_of_letters]
# list_of_words == ["my", "dog", "skip"]

Or sometimes a little more functional:

list_of_words = map(lambda x: "".join(x), lists_of_letters)

I'm wondering if there is a better way to write the function needed for the map call than using a lambda expression. I'm trying to learn the operator and functools to expand my python functional programming chops, but I can't seem to find a clear way to use them in this case.

Upvotes: 3

Views: 286

Answers (2)

david king
david king

Reputation: 758

In this case you can actually just say map(''.join, lists_of_letters):

In [1]: lists_of_letters = [["m", "y"], ["d", "o", "g"], ["s", "k", "i", "p"]]
In [2]: map(''.join, lists_of_letters)
Out[2]: ['my', 'dog', 'skip']

because ''.join is itself a function (a bound method on the empty string) that takes a single argument:

In [3]: ''.join
Out[3]: <built-in method join of str object at 0x100258620>

That said, here it may not be better per se because it's a bit less readable IMO

Upvotes: 5

NPE
NPE

Reputation: 500495

You don't need the lambda function here:

In [26]: map("".join, lists_of_letters)
Out[26]: ['my', 'dog', 'skip']

Upvotes: 1

Related Questions