static variables?

Mike Dean klaatu at evertek.net
Tue Nov 19 21:08:00 EST 2002


On Tuesday 19 November 2002 11:37 am, Michele Simionato <mis6 at pitt.edu> 
wrote in comp.lang.python:
> 
> A simple trick to simulate static variables by passing an optional
> mutable object is the following:
> 
> def f(x,i=[0]): # i[0] is the "static" variable
>     i[0]+=1
>     return x+i[0]
> 
> print f(0),f(0),f(0) #--> 1,2,3

I've seen this trick a time or two before and always wondered - why does 
it work?  Why does Python remember the changed list as the function's 
default value, rather than reverting back to the list that was 
specified when the function was defined?  At first glance it seems a 
bit non-intuitive.

Thanks,
Michael



More information about the Python-list mailing list