Suggestion for impriving list comprehensions
Tom Good
Tom_Good1 at excite.com
Fri Jul 27 14:23:38 EDT 2001
"Tim Peters" <tim.one at home.com> wrote in message news:<mailman.996205196.16876.python-list at python.org>...
[snip]
>
> There's something at least a *little* off with the dance between generators
> and iterators, but I'm not clear on exactly what and haven't had more time
> to consider it. Part of it seems to be that
>
> for x in whatever:
>
> magically applies iter() to whatever under the covers (nothing off there),
> but if "whatever" is a generator(-function), iter(whatever) is an error.
>
> I don't know *why* that seems a little bit off, because it makes perfect
> sense <wink>. But play with it long enough and I wouldn't be surprised if
> you thought so too.
>
> if-so-it's-in-need-of-articulation-ly y'rs - tim
I agree. Consider the following:
>>> from __future__ import generators
>>> def g():
... yield 1
... yield 2
...
>>> i = g()
>>> i.next()
1
>>> i = iter(g())
>>> i.next()
1
>>> i = iter(g)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: iter() of non-sequence
>>>
iter(g) doesn't work, but it somehow feels as if it should.
>>> i = iter([1,2,3,4,5])
>>> j = iter(i)
This *does* work, and maybe that explains why iter(g) feels OK.
Anyway, this is the kind of thing that ought to go in a
generators/iterators tutorial.
Tom
More information about the Python-list
mailing list