Re: [Tutor] Python function seem to have a memory ???
by Danny Yoo other posts by this author
Aug 13 2001 12:12AM messages near this date
Re: [Tutor] Python function seem to have a memory ???
|
Re: [Tutor] Python function seem to have a memory ???
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]
###
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Simon Vandemoortele
dman
Danny Yoo
Kalle Svensson
Danny Yoo
Lloyd Kvam
|