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>

<p>Comprehensions and generator expressions have their own scope, so you can put it in one of those:</p>

<pre><code>&gt;&gt;&gt; def getindex():
...     return 1
...
&gt;&gt;&gt; a,b,c = range(2), range(3,5), 'abc'
&gt;&gt;&gt; next(print(a[x], b[x], c[x]) for x in [getindex()])
1 4 b
&gt;&gt;&gt; x
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'x' is not defined
</code></pre>

<p>But you really don't have to worry about that sort of thing. That's one of Python's selling points.</p>

<p>For those using Python 2:</p>

<pre><code>&gt;&gt;&gt; print next(' '.join(map(str, [a[x], b[x], c[x]])) for x in [getindex()])
1 4 b
</code></pre>

<p>Consider using Python 3, so you don't have to deal with <code>print</code> as a statement.</p>

python