Efficient implementation of deeply nested lists

Kay Schluehr kay.schluehr at gmx.net
Thu Jan 19 15:25:29 CET 2006


Peter Otten wrote:
> Kay Schluehr wrote:
>
> > I want to manipulate a deeply nested list in a generic way at a
> > determined place. Given a sequence of constant objects a1, a2, ..., aN
> > and a variable x. Now construct a list from them recursively:
> >
> > L = [a1, [a2, [....[aN, [x]]...]]
> >
> > The value of x is the only one to be changed. With each value of x a
> > new instance of L is needed so that we actually have a function:
> >
> > L = lambda x: [a1, [a2, [....[aN, [x]]...]]
> >
> > I'm seeking for an efficient implementation that does not recompute the
> > whole list each time. Any ideas?
>
> I'd say you are nesting the wrong way.

The structure of the sequence is *not* optional.

>
> >>> items = make_list(range(10))
> >>> def make_list(items):
> ...     return reduce(lambda *args: args,  items)
> ...
> >>> def update_value(items, value):
> ...     return items[0], value
> ...
> >>> items = make_list(range(10))
> >>> items
> (((((((((0, 1), 2), 3), 4), 5), 6), 7), 8), 9)
> >>> update_value(items, 42)
> (((((((((0, 1), 2), 3), 4), 5), 6), 7), 8), 42)
>
> Obviously I must be missing something. What?

The structure of the sequence is *not* optional. Of course you can also
take the original sequence and apply:

>>> L = list([a1, [a2, [....[aN, [x]]...]])  # shallow copy
>>> L[0] = b

but it is intended to change the most inner element. I guess there is
no way in doing it without a deepcopy / full list construction.
Kay




More information about the Python-list mailing list