Most Pythonic way to concatenate strings

Given this harmless little list:

>>> lst = ['o','s','s','a','m','a']

My goal is to pythonically concatenate the little devils using one of the following ways:

A. plain ol' string function to get the job done, short, no imports

>>> ''.join(lst)
'ossama'

B. lambda, lambda, lambda

>>> reduce(lambda x, y: x + y, lst)
'ossama'

C. globalization (do nothing, import everything)

>>> import functools, operator
>>> functools.reduce(operator.add, lst)
'ossama'

Please suggest other pythonic ways to achieve this magnanimous task.

Please rank (pythonic level) and rate solutions giving concise explanations.

In this case, is the most pythonic solution the best coding solution?


Solution 1:

''.join(lst)

the only pythonic way:

  • clear (that what all the big boys do and what they expect to see),
  • simple (no additional imports needed, stable across all versions),
  • fast (written in C) and
  • concise (on an empty string join elements of iterable!).

Solution 2:

Have a look at Guido's essay on python optimization, it covers converting lists of numbers to strings. Unless you have a good reason to do otherwise, use the join example.

Solution 3:

Of course it's join. How do I know? Let's do it in a really stupid way:
If the problem was only adding 2 strings, you'd most likely use str1 + str2. What does it take to get that to the next level? Instinctively, for most (I think), will be to use sum. Let's see how that goes:

In [1]: example = ['a', 'b', 'c']
In [2]: sum(example, '')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython console> in <module>()
TypeError: sum() can't sum strings [use ''.join(seq) instead]

Wow! Python simply told me what to use! :)

Solution 4:

Here's the least Pythonic way:

out = ""
for x in range(len(lst)):
  for y in range(len(lst)):
    if x + y == len(lst)-1:
        out = lst[y] + out

Solution 5:

I myself use the "join" way, but from python 2.6 there is a base type that is little used: bytearray.

Bytearrays can be incredible useful -- for string containing texts, since the best thing is to have then in unicode, the "join" way is the way to go -- but if you are dealing with binary data instead, bytearrays can be both more pythonic and more efficient:

>>> lst = ['o','s','s','a','m','a']
>>> a = bytearray(lst)
>>> a
bytearray(b'ossama')
>>> print a
ossama

it is a built in data type: no imports needed - just use then -- and you can use a bytearray isntead of a list to start with - so they should be more efficinet than the "join", since there is no data copying to get the string representation for a bytearray.