How to define a temporary variable in python?
<p>Does python have a "temporary" or "very local" variable facility?  I am looking for a one-liner and I want to keep my variable space tidy.</p>

<p>I would like to do something like this:</p>

<pre><code>...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no longer defined...
</code></pre>

<p>The variable ix would be undefined outside of the one line.</p>

<p>Perhaps this pseudo-code is more clear:</p>

<pre><code>...a and b are populated lists earlier in code...
{ix=getindex(); answer = f(a[ix]) + g(b[ix])}
</code></pre>

<p>where ix does not exist outside of the bracket.</p>

<blockquote>
  <p>Does python have a "temporary" or "very local" variable facility? </p>
</blockquote>

<p>yes, it's called a block, e.g. a function:</p>

<pre><code>def foo(*args):
    bar = 'some value' # only visible within foo
    print bar # works
foo()
&gt; some value
print bar # does not work, bar is not in the module's scope
&gt; NameError: name 'bar' is not defined
</code></pre>

<p>Note that any value is temporary in the sense that it is only guaranteed to stay allocated as long as a name is bound to it. You can unbind by calling <code>del</code>:</p>

<pre><code>bar = 'foo'
print bar # works
&gt; foo
del bar
print bar #Â fails
&gt; NameError: name 'bar' is not defined
</code></pre>

<p>Note that this does not directly deallocate the string object that is <code>'foo'</code>. That's the job of Python's garbage collector which will clean up after you. In almost all circumstances there is however no need to deal with unbinding or the gc explicitely. Just use variables and enjoy the Python livestyle.</p>

python