How call arguments stack works in Python?
<p>I am learning python and trying to get idea how stack works in python.  I have some doubts. I know how stack work and i have read many articles and tutorials about it. I have read many threads on stackoverflow they are all good, still I have some doubts.</p>

<p>As far I have read stack stores and return values of function. It work by LIFO principal.</p>

<p>Only first value of the stack will return and store at top.</p>

<p>So my question is - suppose there are four variables:</p>

<pre><code>a = 9
b = 2
c = 13
d = 4
</code></pre>

<p>They are stored in stack in order in which function call the value, for example:</p>

<pre><code>sum = a + d
sum = b + c

a = 9
d = 4
b = 2
c = 13
</code></pre>

<p>and they will return from top to bottom. Now my confusion is - if any operation requires to use <code>d</code> and <code>c</code>, while stack return values from the top, how stack will get the values <code>d</code> and <code>c</code>, as long as they are in middle of stack. Will stack first return a and then return d ??</p>

<p>That's the confusion.</p>

<p>Although stacks work as a LIFO, you have to be careful about exactly which data structures are being stacked. For instance, many programming languages use a stack to store parameters and local variables when calling a function. But the thing that is being stacked is the entire call frame, not the individual variables in the frame. </p>

<p>In C, for instance, I may have local variables a, b, c, d "on the stack" but that means that they are stored at a known fixed offset from the start of the frame. The variables can be accessed in any order and they don't move around (apart from optimizations the compiler may be doing). </p>

<p>Python makes it a bit more complicated. In CPython at least, there is a stack frame under the covers, but the local variables you see are actually stored in an an array (see shadowranger's note below)  on a function instance object which makes up the function's local namespace. All variables can be accessed through the dict at any time.</p>

<p>In these cases, the local variables are not themselves a LIFO and can be accessed arbitrarily as long as you know their offset or name in the namespace dict.</p>

python stack callstack