python list to string which one is faster join vs str vs

[Python] List To String: Which One Is Faster? join() vs str() vs +=

When converting a list to a string in Python, str.join() performed 3.47x faster than type casting with str(list) and 6.17x faster than looping over the list elements and concatenating them to a new string. This test was performed over 10 million iterations on Google Colab.

import time

test_list = list('ABCDE')

# Testing str.join()
start = time.process_time()
for i in range(10_000_000):
  t = ''.join(test_list)
print(time.process_time() - start)

# Testing str(list)
start = time.process_time()
for i in range(10_000_000):
  t = str(test_list)
print(time.process_time() - start)

# Testing looping over list elements
start = time.process_time()
for i in range(10_000_000):
  t = ''
  for i, char in enumerate(test_list):
    t += char
print(time.process_time() - start)

>>> 1.9363144830000039
>>> 6.709076755000005
>>> 11.945383304000003

Please note that this test was performed on Google Colab, which is a cloud-based Jupyter Notebook environment that runs on Google Cloud Platform. The results may vary depending on the environment, and on the runtime type you choose.

Also, depending on the use case, the performance of the three methods may vary. It’s a good idea to test the performance of each method in your environment before using it in production.