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?
The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
String join is significantly faster then concatenation.
String concatenation It can be a bit surprising, but this code actually runs in O(N2) time. The reason is that in Java strings are immutable, and as a result, each time you append to the string new string object is created.
''.join(lst)
the only pythonic way:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With