int to str in list elements..

Alex Martelli aleax at mac.com
Mon Oct 15 05:25:15 CEST 2007


Abandoned <besturk at gmail.com> wrote:

> Hi..
> I have a list as a=[1, 2, 3 .... ] (4 million elements)
> and
> b=",".join(a)
> than
> TypeError: sequence item 0: expected string, int found
> I want to change list to  a=['1','2','3'] but i don't want to use FOR
> because my list very very big.
> I'm sorry my bad english.
> King regards

Try b=','.join(map(str, a)) -- it WILL take up some memory (temporarily)
to build the huge resulting string, but there's no real way to avoid
that.

It does run a bit faster than a genexp with for...:

brain:~ alex$ python -mtimeit -s'a=range(4000*1000)'
'b=",".join(map(str,a))'
10 loops, best of 3: 3.37 sec per loop

brain:~ alex$ python -mtimeit -s'a=range(4000*1000)' 'b=",".join(str(x)
for x i
n a)'
10 loops, best of 3: 4.36 sec per loop


Alex



More information about the Python-list mailing list