[Tutor] variable within function retains value
Kent Johnson
kent37 at tds.net
Thu Jun 18 13:02:26 CEST 2009
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
>
>
>>>> def flatten(myList,start=[]):
> """ Flatten nested lists
> >>> flatten([1,[2,[3,4],5]],[])
> [1, 2, 3, 4, 5]
> """
> for i in myList:
> if type(i) != list:
> start.append(i)
> else: flatten(i,start)
> return start
>
>
>>>> flatten([1,[2,[3,4],5]])
> [1, 2, 3, 4, 5]
>
>>>> flatten([1,[2,[3,4],5]])
> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>
>>>> flatten([1,[2,[3,4],5]],[])
> [1, 2, 3, 4, 5]
More information about the Tutor
mailing list