[Tutor] Python function seem to have a memory ???

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 12 Aug 2001 17:12:19 -0700 (PDT)


On Sun, 12 Aug 2001, dman wrote:

> Others have already explained why it works the way it does, but
> haven't given an example of how to get a default argument value of a
> new empty list each time the function is called.

Ah!  One technique that people use is to set the default argument to
'None'.  Then, if we see that it's still None by the time the function's
actually in motion, then we can create a new list.

Here're an example:

###
def SliceDiceList(my_sequence=None):
    "It slices, it dices, ..."
    if my_sequence == None: my_sequence = []
    diced_list = []
    for i in range(0, len(my_sequence), 2):
        diced_list.append(my_sequence[i])
    return diced_list
###


And a trial run through:

###
>>> SliceDiceList("abcdefghijklmnopqrstuvwxyz")
['a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y']
>>> SliceDiceList()
[]
>>> SliceDiceList([3, 1, 4, 1, 5, 9, 2, 6])
[3, 4, 5, 2]
###