Converting to/getting original list object from string representation of original list object in python
<p>I want to convert string representation of arbitrary list back to the original-like list object as explained in the code below:</p>

<pre><code>list1 = [1,2,3,4]
list1str = str(list1) 
str2list1 = list1str[1:-1].split(",") #stripping off square brackets from [1,2,3,4] and then splitting
print(list1)      #[1,2,3,4]
print(str(list1)) #[1,2,3,4]
print(str2list1)  #['1', ' 2', ' 3', ' 4']    
                  #Notice that the elements are of string types. 
                  #Also there is a prefix empty space in ' 2' (and also in ' 3' and ' 4')
                  # --&gt; I will like str2list1 to be ['1', ' 2', ' 3', ' 4']
</code></pre>

<p>Also if we are dealing with nested lists:</p>

<pre><code>list2 = [1,2,['a','b'],4]
list2str = str(list2)
str2list2 = list2str[1:-1].split(",")
print(list2)      #[1, 2, ['a', 'b'], 4]
print(str(list2)) #[1, 2, ['a', 'b'], 4]
print(str2list2)  #['1', ' 2', " ['a'", " 'b']", ' 4']
                  # --&gt; I will like str2list2 to be [1, 2, ['a', 'b'], 4]
</code></pre>

<p>How can I get exact the original list from its string representation?</p>

<p>Easiest way, use <em>eval()</em>:</p>

<pre><code>lst = "[1, 2, 3, 4, ['a', 'b'], 5, 6]"
newlst = eval(lst)
</code></pre>

<p>so the newlst will be the exact python list you want</p>

<pre><code>print (newlst)
# [1, 2, 3, 4, ['a', 'b'], 5, 6]
</code></pre>

<p>There's one more way to do what you want with <em>exec()</em>:</p>

<pre><code>exec("newlst = {}".format(lst))
</code></pre>

<p>exec will actually treat the string as a python command/syntax.</p>

python