Basic list/dictionary question
Mick Krippendorf
mad.mick at gmx.de
Wed Nov 11 10:14:59 EST 2009
Ralax wrote:
> On Nov 11, 8:58 pm, Chris Rebert <c... at rebertia.com> wrote:
>> In [2]: def foo(z, a=[]):
>> ...: a.append(z)
>> ...: return a
>> ...:
>>
>> In [3]: foo(1)
>> Out[3]: [1]
>>
>> In [4]: foo(2)
>> Out[4]: [1, 2]
>>
>> In [5]: foo(2)
>> Out[5]: [1, 2, 2]
>>
>> In [6]: foo(3)
>> Out[6]: [1, 2, 2, 3]
>>
>> In [7]: foo(4,[])
>> Out[7]: [4]
>>
>> In [8]: foo(5)
>> Out[8]: [1, 2, 2, 3, 5]
>
> Usefull!
I think Chris post was meant as a warning, but yes, it is useful
sometimes. Here's a less error-prone version:
>>> def bar():
... def foo(z, a=[]):
... a.append(z)
... return a
... return foo
...
>>> f = bar()
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> g = bar()
>>> g(3)
[3]
>>> g(4)
[3, 4]
Regards,
Mick.
More information about the Python-list
mailing list