Appending to Long Strings in Python

Be careful when repeatedly appending to a string in Python. Because strings are immutable, each time you change one, a new object is created. The code below is very intuitive:

r=1000000

s = ''
for i in range(r):
    s += str(i)

But it doesn’t perform too well.

A better approach is to create and append to a list and then convert it to a string using ''.join(l), like this:

r=1000000

l = []
for i in range(r):
    l.append(str(i))
s =''.join(l)

And an even slightly faster approach is to use join() with a list comprehension:

r=1000000

s = ''.join([str(i) for i in range(r)])

Here are the three methods compared with timeit:Methods for concatenating strings

As you can see, the latter two methods, which modify a list and then convert it to a string, run 4 to 5 times as quickly. The larger the string (i.e., the bigger the object), the bigger the difference will be.


Related Training: Advanced Python

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.