Strange generator problem

Paul Hankin paul.hankin at
Fri Oct 5 11:34:53 CEST 2007

On Oct 5, 10:23 am, Joost Cassee <jo... at> wrote:
> Hello all,
> I bumped into an unexpected problem using generators. Consider this code:
> def test(s):
>     return _test([], [], s)
> def _test(s1, s2, s):
>     if s:
>         s1.append(s.pop())
>         for x in _test(s1, s2, s):
>             yield x
>         s2.append(s1.pop())
>         for x in _test(s1, s2, s):
>             yield x
>         s.append(s2.pop())
>     else:
>         yield s1, s2

Lists aren't copied when they're yielded, so you're returning the same
lists (with different elements) each time. Your final list looks like
[(s1, s2), (s1, s2), ...] and as it happens, s1 and s2 are both [] by
the end.

You can fix it by copying the lists manually before yielding them, or
using a better sub-list algorithm :)

Paul Hankin

More information about the Python-list mailing list