transforming a list into a string

Roy Smith roy at
Sat Jul 31 15:06:47 CEST 2004

In article <pan.2004. at>,
 jblazi <jblazi at> wrote:

> Let us assume I have a list like
> ['1','2','7','8','12','13]

I'm assuming there's supposed to be another single-quote after the 13?

> and would like to transoform it into the string
> '{1,2},{7,8},{12,13}'

This works, and is pretty straight-forward:

source = ['1','2','7','8','12','13']
temp = []

while source:
    x = source.pop(0)
    y = source.pop(0)
    temp.append ('{%s,%s}' % (x, y))

result = ','.join (temp)
print result

This prints what you want:

$ /tmp/ 

Accumulating the repeating bits of the result string in a list, and then 
putting them together with a join operation is a common idiom in python.  
You can build up strings by doing string addition:

temp = temp + '{%s,%s}' % (x, y)

This will have the same result, but suffers from quadratic run times as 
it keeps building and destroying immutable strings.

> Which is the simplest way of achiebing this? (The list is in fact much
> longer and I may have to cut the resulting strings into chunks of 100 or
> so.)

How long is "much longer", and how important is it that this runs fast?  
The code above runs in O(n).  You can probably play some tricks to tweak 
the speed a little, but in the big picture, you're not going to do any 
better than O(n).

The above code also assumes you have an even number of items in source, 
and will bomb if you don't.  You probably want to fix that :-)

More information about the Python-list mailing list