14
\$\begingroup\$

This is a question for golfing in .

Suppose you have two lists of strings, and you want to concatenate the corresponding entries from each list. E.g. with a=list("abcd") and b=list("1234"), calculate ["a1","b2","c3","d4"].

This is trivial in array-based programming languages, where operations generally apply memberwise to lists. For example, in my golfing language Pip, the code is simply a.b. But in Python, it's not so easy.

The Pythonic way is probably to use zip and a list comprehension (25 chars):

[x+y for x,y in zip(a,b)]

Another method is map with a lambda function (23):

map(lambda x,y:x+y,a,b)

The following is the shortest I've come up with (21):

map("".join,zip(a,b))

Is there any shorter method?

Assume that the lists are the same length and that some kind of iterable is all that's needed (so a map object is fine in Python 3).

\$\endgroup\$
3
  • \$\begingroup\$ possible duplicate of Tips for golfing in Python \$\endgroup\$
    – Mast
    Commented May 6, 2015 at 12:29
  • \$\begingroup\$ @Mast Does the tips list contain an answer which addresses this specific question? \$\endgroup\$ Commented May 6, 2015 at 18:23
  • \$\begingroup\$ @MartinBüttner If it isn't, it should. Prevents cluttering and keeps all the tricks togeter, etc. \$\endgroup\$
    – Mast
    Commented May 6, 2015 at 19:47

1 Answer 1

14
\$\begingroup\$

20 chars

map(str.__add__,a,b)

Uses the build-in method string addition method __add__ that is invoked by + on strings in place of your anonymous function lambda x,y:x+y.

\$\endgroup\$
2
  • \$\begingroup\$ You know, I thought of str.__add__ but for some reason didn't check to see if it was shorter. \$\endgroup\$
    – DLosc
    Commented May 6, 2015 at 2:20
  • 1
    \$\begingroup\$ @DLosc the real advantage of this answer is using map with multiple iterables, which dis the zipping automatically. Without that it wouldn't be shorter. Note that if in your code you have to access some of the __*__ methods it may be shorter to do from operator import * and then use map(add,a,b). \$\endgroup\$
    – Bakuriu
    Commented May 6, 2015 at 6:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.