Search code examples
pythonconcatenation

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. A plain old 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'

What are 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

  • 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.