What is the most efficient way to concatenate many strings together?

Technology CommunityCategory: PythonWhat is the most efficient way to concatenate many strings together?
VietMX Staff asked 3 years ago

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, I would recommend to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)