title: NameError on variable that has been defined within the function?
body: <p>I am trying to iterate over a dictionary to create new lists on a function. I get NameError when calling one of the variables at the end to create a dataframe.</p>
  <pre><code>def multiply(number):
  
  list1 = []
  list2 = []
  
  appendDict = {
  'list1': '1',
  'list2': '2'}
  
  for i in range(10):
      for k, v in appendDict.items():
          eval(k).append(i*number*int(v))
          eval(k).append(i*number*int(v))
  
  
  df = {k:eval(k) for k, v in appendDict.items()}
  df = pd.DataFrame(df)
  
  return df
  
  
  
  print(multiply(1))
  </code></pre>
  <p>When I try running the code in the very same file, I get a <strong>NameError</strong>, stating that the list1 variable is not defined.</p>
  <pre><code>&quot;NameError: name 'list1' is not defined&quot; 
  </code></pre>
  <p>I understand that it is not defined OUTSIDE of the function, but if it is already defined IN the function and only used IN the function, why do I need to define it as global? When defining the variable as global, the problem disappears but I want to understand why.</p>
  <p>As a side note, if I run this small loop <strong>within</strong> the function, it prints out the contents of the variables seamlessly, without them having to be defined as global variables. The problem comes when trying to build a dictionary out of the variables.</p>
  <pre><code>   for k, v in appendDict.items():
         print(eval(k))
     
  </code></pre>
  <p><strong>UPDATE</strong>: Solved by creating a scope variable and inserting it in the eval function.</p>
  <pre><code>scope=locals()
  df = {k:eval(k, scope) for k, v in appendDict.items()}
  </code></pre>
  <p>This was a duplicate question:
  <a href="https://stackoverflow.com/questions/45194934/eval-fails-in-list-comprehension">eval fails in list comprehension</a>
  <a href="https://stackoverflow.com/questions/36616739/python-how-can-i-run-eval-in-the-local-scope-of-a-function?noredirect=1&amp;lq=1">Python: How can I run eval() in the local scope of a function</a></p>