Python: Fastest — Convert list of integers to comma separated string

Recently I had to look for ways to converts a list of integers to a comma separated string in python.

A simple google search lead me to a couple of stack overflow articles [1] and [2], where I found a number of ways to complete the task. However, I had to find the fastest way to accomplish the task as I had to convert integer lists of length between 10000 and 12000, that too a multiple times. So, I decided to run some experiments.

Here is the sample list to convert, with the 7 contenders and outputs:

Except the last one, every other contender generates similar output. However, in a comma separated string, spaces after commas hardly makes a difference.

Experiment

To find the fastest way to convert, I made use of the timeit module.

timeit.repeat(setup, stmt, repeat=5, number=1000)

where

setup usually takes import statements and variable initialization.

stmt is the actual statement to measure.

The statement will be run 1000 times to get the average time to complete and getting 5 average times will help weed out a run that could have being bogged down by some other process running on the machine.

Code

Results

The values in green is the lowest execution time taken by a contender.

As you can see the unusual contender that uses the inbuilt function in list to convert to a comma separated string is by far the fastest. The slowest one I would say is the method using StringIO.

If you take the fastest run from each of the contenders, the str-list method is faster then the old-style method by almost 3 seconds.

I ran this experiment on a 3 different machines with varying configurations and the results were similar. The str-list method was the fastest.

Hope this experiment helps you as it helped me.

One last point, some of contenders also work on other lists types as well.

Computer Vision | Machine Learning | Deep Learning https://arccoder.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store