[Tutor] recursive loop strange behavior
Jeff Shannon
jeff@ccvcorp.com
Tue Jan 14 13:38:10 2003
Darwin Chrisman wrote:
> This is the function I created:
> def factor(num,primes,tempres=[]):
> [...]
>
> the function itself seems to work fine, however if I dont specify an
> empty list for tempres when I call the function the next time I call
> it tempres defaults to the last value the function returned.
> I can't figure out what I am doing wrong. Any help?
The problem here is that Python only evaluates default arguments *once*,
when the function is defined -- not each time it's called, which is what
you seem to be expecting. So the second (and subsequent) times that you
call factor(), you're getting the *same* list that it started out with
-- and now it's not empty.
The quickest solution is to change the default to be None, and test for
that inside your function.
def factor(num, primes, res = None):
if not res:
res = []
[...]
This way, you'll create a *new* empty list every time you call this
function without a res argument.
Jeff Shannon
Technician/Programmer
Credit International