Chapter 9 Lists

9.6 Lists and Function Return ValuesΒΆ

A list object can be constructed in the execution of the function body during a function call, and taken as the return value. For example, consider a function that takes a list of numbers as the only argument, and returns a list containing all the positive numbers in the list. The function can be written using the idea of generalized summation, with the output s being initialized as an empty list, and incrementally extended by iterating over all the items of the argument.

In the program above, the function findpositive iterates through the items of l. At each iteration, if the current item is positive, it is appended to the output s; otherwise no action is taken.

As introduced previouly, in memory, each call to findpositive constructs a new local scope, with its own binding table. When the function body is executed, a new list object is created by the first statement s = [ ], and bound to the local identifier s. s is updated through the execution of the for statement in the function body, and taken as the return value of the function call.

The three calls to findpositive in the code return three different list objects, which are bound to the global identifiers l1, l2 and l3, respectively. After the function calls, the local binding tables of the function calls will be removed by the garbage collector. However, the list objects that are returned by the function calls will not be removed, because they are still bound to the global identifiers l1, l2 and l3.

As another example of lists and return values, the function negate below takes a list argument and returns a list object that contains the negations of the items of the argument. It works by making a copy of the list argument, and then iterating through the copy and negating each value.

Note that the for loop in the above example must iterate through the indices of s instead of the items of s directly, because a modification to s requires the use of item indices to specify the items to be changed.

© Copyright 2024 GS Ng.

Next Section - 9.7 Initializing a List