[Tutor] list to string and string to list

Alan Gauld alan.gauld at btinternet.com
Fri Apr 17 02:04:39 CEST 2009

"johnf" <jfabiani at yolo.com> wrote

>> I want to save the list to the field and when I retrieve the string 
>> convert
>> it back to a list.
>> But this does NOT work.
>> mylist=[1,2,3,4]
>> mystr=str(mylist)
>> newlist= list(mystr)
>> I keep thinking there must be a simple way of get this done.
> Is this a good way?
> newlist = eval(mystr)

eval has all sorts of security implications so I wouldn't recommend
it where you are reading data fropm an external source.

One thing that might work is this:

>>> L = [1,2,3,4,5]
>>> s1 = ','.join(str(n) for n in L)
>>> s1
>>> newlist = [int(n) for n in s1.split(',')]
>>> newlist
[1, 2, 3, 4, 5]

Provided your original data doesn't have commas to start with
it should work, I think... And the data needs to be pretty
homogenous to allow a single conversion function.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list