Use strings in a list as variable names in Python
<p>I have a list of string elements like <code>user_contract = ['ZNZ6','TNZ6','ZBZ6']</code></p>

<p>I have a data set which has nested list structure like <code>data = [[1,2,3],[4,5,6],[7,8,9]]</code></p>

<p>I want to assign each of the <code>user_contract</code> strings as variable names for each of the <code>data</code> nested list, in the respective order. </p>

<p>I know I can do this manually by typing <code>ZNZ6, TNZ6, ZBZ6 = data</code>. I don't think this is flexible enough, and I would have to manually change this line every time I change the names in <code>user_contract</code>.</p>

<p>Is there a way where I can make use of the <code>user_contract</code> variable to assign data to each of its elements?</p>

<p>You can use <code>exec</code> to evaluate expressions and assign to variables dynamically:</p>

<pre><code>&gt;&gt;&gt; names = ','.join(user_contract)
&gt;&gt;&gt; exec('{:s} = {:s}'.format(names, str(data)))
</code></pre>

python list