A ListComp that maintains its own state

Carl Banks invalidemail at aerojockey.com
Wed Feb 9 17:05:52 EST 2005


Bernhard Herzog wrote:
> Michael Spencer <mahs at telcopartners.com> writes:
>
> > So, here's factorial in one line:
> > # state refers to list of state history - it is initialized to [1]
> > # on any iteration, the previous state is in state[-1]
> > # the expression also uses the trick of list.append() => None
> > # to both update the state, and return the last state
> >
> >  >>> [state.append(state[-1] * symbol) or state[-1]
> > ...         for symbol, state in
it.izip(range(1,10),it.repeat([1]))
> > ...             ]
> > [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
> >  >>>
>
> There's no need for repeat:
>
> >>> [state.append(state[-1] * symbol) or state[-1]
>         for state in [[1]]
>         for symbol in range(1, 10)]
> [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]


Nope, that's just too convenient.  Now I'm going to end up doing this
all the time.


-- 
CARL BANKS




More information about the Python-list mailing list