[Tutor] variable within function retains value

karma dorjetarap at googlemail.com
Thu Jun 18 13:40:56 CEST 2009


Excellent, thanks for that answer Kent. Also thanks for the link


2009/6/18 Kent Johnson <kent37 at tds.net>:
> On Thu, Jun 18, 2009 at 6:21 AM, karma<dorjetarap at googlemail.com> wrote:
>> Hi All,
>>
>> I'm trying to write a function that flattens a list. However after I
>> call the function more than once, it appends the result (a list) from
>> the second call with the first. I can get around it by either setting
>> the list to an empty one before calling the function, but I would like
>> to keep it in the function, another alternative I found was to pass an
>> empty list as an argument.
>>
>> Can someone explain how python keeps track of variables within
>> functions (I was expecting the variable to be destroyed after a value
>> was returned). Also what is a better way to handle this?
>
> Default arguments are only evaluated once, when the function is
> compiled, so the start list is shared between invocations of flatten.
> This is a FAQ:
> http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
>
> Another solution - it's easy to rewrite flatten() so it doesnt' need a
> default argument:
>
> In [1]: def flatten(myList):
>   ...:     start = []
>   ...:     for i in myList:
>   ...:         if type(i) != list:
>   ...:             start.append(i)
>   ...:         else:
>   ...:             start.extend(flatten(i))
>   ...:     return start
>
> Kent
>
> PS Please don't quote unrelated questions when posting.
>
>> Thanks


More information about the Tutor mailing list