list to string

Greg Landrum gReGlAnDrUm at earthlink.net
Wed Feb 28 02:50:54 CET 2001


"Glen Mettler" <gem at hsv.crc.com> wrote in message
news:97haor$flu$1 at hobbes2.crc.com...
> I couldn't get "for element in mylist" to work but this does:
>
> mylist = ['d','o','g']
> mystring = ''
> for j in range(len(mylist)):
>     mystring= mystring+"".join(mylist[j])
> print mystring
>

This is a lot more work than you need to be doing.
If you just want to convert the array into a string the simplest way
possible:
mylist = ['d','o','g']
mystring = ''.join(mylist)
print mystring

Though this may be somewhat ugly (depending upon who you ask), it is very
simple.

You can also loop over the list.  Here are a couple of ways:

One way to loop over all the elements in the list (like you are doing) is:
mylist = ['d','o','g']
mystring = ''
for j in range(len(mylist)):
  mystring = mystring + mylist[j]

Another way to loop over all the elements in the list is:
mylist = ['d','o','g']
mystring = ''
for item in mylist:
  mystring = mystring + item

> I am very, very new to Python so this may not be very elegant but it does
> work

It's still a good idea to learn more efficient ways of doing things early in
your learning experience.  It'll help you avoid developing bad habits that
you'll have to break later.

If you would like to see what I mean by efficiency, try running a list 10000
elements long through your code and seeing how long it takes in comparison
to the ''.join() solution.  (hint, you can generate a list which is 10000
elements long like this: mylist = ['d']*10000)

I hope this helps,
-greg







More information about the Python-list mailing list