how to convert type of variables in python?
<p>Suppose</p>

<pre><code>    type(a) = &lt;type 'numpy.ndarray'&gt;
</code></pre>

<p>now I have another variable <code>b</code> (maybe a <code>&lt;type 'list'&gt;</code>), I want to convert it into the same type of <code>a</code>. How to do this? For example, </p>

<pre><code>    &gt;&gt;&gt; type(a)
    &lt;type 'numpy.ndarray'&gt;
    &gt;&gt;&gt; b = [[[100, 200, 300]]]
    &gt;&gt;&gt; type(b)
    &lt;type 'list'&gt;
</code></pre>

<p>Now, I want to </p>

<pre><code>    &gt;&gt;&gt; type(b)
    &lt;type 'numpy.ndarray'&gt;
</code></pre>

<p>I want to do this in a python script. I don't know in advance what is the type of <code>a</code>. I just take <code>numpy.ndarray</code> as an example.</p>

<p><strong>UPDATE:</strong></p>

<p>In fact, in the python script, it receive some strings from <code>sys.argv</code>. And then it will assign these strings into some predefined variables in this script. These predefined variables may be <code>int</code>, <code>list</code>, <code>numpy.ndarray</code>, or else. For <code>int</code> or <code>list</code>, this can be done by <code>from ast import literal_eval; MyDict[sys.argv[1]] = literal_eval(sys.argv[2])</code>. But if <code>MyDict[sys.argv[1]]</code> is a <code>numpy.ndarray</code>, the <code>literal_eval</code> cann't reassign the list <code>[[[100, 200, 300]]]</code> into a <code>numpy.ndarray</code>. So I'm seeking a more effective way to do this.</p>

<p>Presumably you don't <em>just</em> want to convert the type; you also want to preserve the existing value.  (Otherwise you could just assign <code>b</code> to an empty object of the new type and be done with it.)</p>

<p>Very generally, you would call the new type's constructor, passing in the old value.  For example, if you have an integer and you want to covert it to a string, call <code>str()</code> on the integer value:</p>

<pre><code>a = 5        # type(a) is &lt;type 'int'&gt;
a = str(a)   # type(a) is now &lt;type 'str'&gt;
</code></pre>

<p>Or to convert a string to a list:</p>

<pre><code>a = "hello"  # type(a) is &lt;type 'str'&gt;
a = list(a)  # type(a) is now &lt;type 'list'&gt;
</code></pre>

<p>However this method is <em>very</em> generic and won't be usable in a lot of cases.</p>

python