3

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I completely forgot that bound methods were first class functions as well. Thats why I wasn't getting anywhere with partial.
1

You don't need the lambda function here:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.