Recursive list comprehension

Peter Otten __peter__ at web.de
Wed Dec 8 15:17:11 EST 2004


Adam DePrince wrote:

> def flatten( i ):
>     try:
>         i = i.__iter__()
>         while 1:
>             j = flatten( i.next() )
>             try:
>                 while 1:
>                     yield j.next()
>             except StopIteration:
>                 pass
>     except AttributeError:
>         yield i

While trying to break your code with a len() > 1 string I noted that strings
don't feature an __iter__ attribute. Therefore obj.__iter__() is not
equivalent to iter(obj) for strings. Do you (plural) know whether this is a
CPython implementation accident or can be relied upon?

Peter




More information about the Python-list mailing list