This is an example tracing through a functions with list parameters and drawing the stack at different points in its execution.

Note that a function can modify the values stored in a list parameter (i.e., the square_smaller function has a side effect of possibly modify the list contents in the passed list).

Consider the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def main():
    l = [2, 4, 6, 7, 3, 5]
    print(l)

    how_many = square_smaller(l, 5)

    print(l)
    print("%d elments were squared" % (how_many))

#######################################
def square_smaller(nums, val):
    """
    This function square any list elment that is less than the passed value.
      nums: a list of numbers
      val: the value to match
      returns: the total number of list elements modified
      side effect: squares all values in the list less than val
    """
    total = 0
    for i in range(len(nums)):
       if (nums[i] < val):
          nums[i] = nums[i]*nums[i]
          total = total + 1

    return total

#######################################
main()

When run, this program’s output is:

$ python test.py
[2, 4, 6, 7, 3, 5]
[4, 16, 6, 7, 9, 5]
3 elments were squared

Here is a drawing of the stack from before the call to square_smaller in main:

liststack0
Figure 1. Stack Diagram before function call.

Here is a drawing of the stack at the point in the exectuion when the square_smaller function has been called, and it is just about to execute its first instruction (its stack frame is set-up with its parameters getting the values of the arguments from the call in main):

liststack1
Figure 2. Stack Diagram at start of functioat start of function.

Here is a drawing of the stack at the point in the exectuion right before the return statment in the square_smaller function:

liststack2
Figure 3. Stack Diagram right before the function returns.

Here is a drawing of the stack after the call to square_smaller function returns (note that the values in the list l have been modified by the function, and the the function’s return value is assigned to main’s local variable `how_many):

liststack3
Figure 4. Stack Diagram after the call.